2017-10-18 1 views
0

私はリアクションを使用して入力フォームを作成しています。 すべての子供の入力があり、値を保存するための独自の状態がありますが、どのように親を処理するかわかりません。私が反応にあまり入力でCOMPEXフォームの使用方法のいくつかの例を見つけることができますリアクト・ハンドル状態の更新

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; 

または:ここ は一例です。 ありがとう!

+0

ScoobyDrew18は正解ですが、このテクニックを習得したときに還元式を調べます – artSir

答えて

3

あなたの状態の一部を親コンポーネントに移動することを検討する必要があるように思えます。 Reactのドキュメントには、thisについての良い記事があります。

要約すると、親に関数を宣言すると、hanleChnage();関数を子コンポーネントの小道具として渡すことができます。

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

コンポーネントの複雑さが増すにつれて、状態管理にReduxを使用すると、アプリケーション内のすべての状態を単一のソースとして扱うことができます。

1

親コンポーネント内の関数(parentFunctionなど)を参照するように、子プロパティ(callParentPropertyなど)を設定します。

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); 
    } 
} 
関連する問題