2016-07-22 64 views
0

我目前正在尝试使用表示和容器组件重构流星的简单教程教程,但遇到了试图访问功能无状态组件中的input的引用的问题。我发现要访问refs,你必须将组件包装在一个有状态的组件中,我使用input访问有状态组件中的ref在React中不起作用?

// import React ... 
import Input from './Input.jsx'; 

const AppWrapper = (props) => { 
    // ... more lines of code 

    <form className="new-task" onSubmit={props.handleSubmit}> 
    <Input /> 
    </form> 
} 

import React, { Component } from 'react'; 

此输入应该是有状态的,因为它使用类语法,至少我认为。

export default class Input extends Component { 

    render() { 
    return (
     <input 
     type="text" 
     ref="textInput" 
     placeholder="Type here to add more todos" 
     /> 
    ) 
    } 
} 

我用裁判的涵盖AppContainer搜索输入的值。

import AppWrapper from '../ui/AppWrapper.js'; 

handleSubmit = (event) => { 
    event.preventDefault(); 
    // find the text field via the React ref 
    console.log(ReactDOM.findDOMNode(this.refs.textInput)); 
    const text = ReactDOM.findDOMNode(this.refs.textInput).value.trim(); 
    ... 
} 

中的console.log的结果是null,所以我输入组件无状态的?我是否需要设置一个构造函数来为this.state设置一个值来使这个组件成为有状态的,或者当我需要使用refs时,我应该放弃使用无状态的功能组件?

+0

'handleSubmit'定义在哪里?'ref'只能从有状态组件中访问。 –

+0

你不能像这样使用裁判。你在一个单独的组件里面做'this.ref',其中textInput不存在。 – jzm

回答

0

或者我应该放弃在我需要使用refs时使用功能无状态组件?

是的。如果组件需要保持对它们呈现的元素的引用,则它们是有状态的。

参考文献可以像这样一个“回调”功能进行设置:

export default class Input extends Component { 

    render() { 
    // the ref is now accessable as this.textInput 
    alert(this.textInput.value) 
    return ( 
     <input 
     type="text" 
     ref={node => this.textInput = node} 
     placeholder="Type here to add more todos" 
     /> 
    ) 
    } 
} 
0

你必须使用裁判时使用状态的组件。在你的handleSubmit事件中,当字段位于单独的组件中时,你调用'this.refs'。

要使用refs,您需要将ref添加到您呈现AppWrapper的位置,并且AppWrapper本身必须是有状态的。

下面是一个例子:

AppWrapper - 这是你的形式

class AppWrapper extends React.Component { 
    render() { 
    return (
     <form 
     ref={f => this._form = f} 
     onSubmit={this.props.handleSubmit}> 
     <Input 
      name="textInput" 
      placeholder="Type here to add more todos" /> 
     </form> 
    ); 
    } 
}; 

输入 - 这是一种可重复使用的文本框组件

const Input = (props) => (
    <input 
    type="text" 
    name={props.name} 
    className="textbox" 
    placeholder={props.placeholder} 
    /> 
); 

应用 - 这是容器组件

class App extends React.Component { 
    constructor() { 
    super(); 
    this.handleSubmit = this.handleSubmit.bind(this); 
    } 

    handleSubmit(event) { 
    event.preventDefault(); 
    const text = this._wrapperComponent._form.textInput.value; 
    console.log(text); 
    } 

    render() { 
    return (
     <AppWrapper 
     handleSubmit={this.handleSubmit} 
     ref={r => this._wrapperComponent = r} 
     /> 
    ); 
    } 
} 

http://codepen.io/jzmmm/pen/BzAqbk?editors=0011

正如你看到的,输入组件是无状态的,并且AppWrapper是有状态的。您现在可以避免使用ReactDOM.findDOMNode,并直接访问textInput。输入必须具有要引用的name属性。

您可以通过将<form>标记移动到App组件中来简化此操作。这将消除一个ref

相关问题