2017-10-18 135 views
0

我正在使用反应来构建一些输入表单。 虽然所有儿童的投入都有自己的国家来存储价值,但我不知道如何处理父母。 这里的例子:反应句柄状态更新

class FormComponent extends Component { 

    constructor(props) { 
     super(props); 

     this.state = { 
      title: null, 
      someAmount: null 
     } 
    } 

    render() { 
     let me = this; 

     return (
      <div> 
       <TextField 
        value={me.state.title} 
        onChange={(proxy, value) => { 
          me.setState({title: value}) 
          me.hanleChnage(); 
         } 
        } 
       /> 
       <TextField 
        value={Number.parseFloat(me.state.someAmount)} 
        onChange={(proxy, value) => { 
          if (!isNaN(Number.parseFloat(value))) { 
           me.setState({someAmount: value}) 
           me.hanleChnage(); 
          } 
         } 
        } 
       /> 
      </div>  
      )  
    } 

    handleChange() { 
     //Calling the parent 
     //State here is outdated 
     this.props.onUpdate && this.props.onUpdate(this.state); 
    } 
} 

export default FormComponent; 

或者在哪里可以找到的COMPEX形式使用的一些例子,在反应太大的投入。 谢谢!

+0

ScoobyDrew18是正确的答案,但是当你掌握了这种技术时, – artSir

回答

3

听起来像你需要考虑移动你的一些状态到父组件。 React文档有关于this的很好的文章。总之,如果你在你的父项中声明了这个函数,你可以将你的hanleChnage();函数作为一个道具传递给你的子组件。

function handleChange() { //do something... } 
... 
<ChildComponent parentOnChange={this.handleChange.bind(this) /> 

当你的成分日益复杂,您可以考虑使用Redux的状态管理,从而起到对您的应用程序的所有国家的单一来源。

1

设置子属性(例如callParentProperty)以引用父组件中的函数(例如parentFunction)。

class ParentComponent extends Component{ 
    parentFunction(parameter) { 
     console.log("This is the form value"); 
     console.log(parameter); 
    } 
    render() { 
     return <FormComponent callParentFunctionProperty={this.parentFunction.bind(this)} /> 
    } 
} 
class FormComponent extends Component { 
    ... 
    handleChange() { 
     ... 
     let formValue = this.state.someAmount; 
     this.props.callParentFunctionProperty(formValue); 
    } 
}