2017-10-18 133 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); 
    } 
}