2017-07-22 3 views
1

を反応させます状態のために。は私の親コンポーネント内

私の親の中で、私が子供のコンポーネントに与える小道具の名前にアクセスしたいと思います。このようにして、親の状態は、レンダリング中の異なるInputFieldに動的にuodateする必要があります。私の関数は次のようになります

inputValue(e) { 
    this.setState({ 
     inputValue: { 
     thisShouldBeTheChildsName: e.target.value 
     } 
    })  
    } 

この関数内で、親の内部でどのように私はアクセスできますか?

+0

これは不明です。コードスニペットまたはコードサンドボックスを使用して、質問を正確に、最小限の例を提供してください。 –

+0

私が行う必要があるのは、親コンポーネント内の子に「名前」として提供した値を取得することだけです。 –

+0

はい、それは本当に明確ではありません、スニペットを提供できますか? – soywod

答えて

1

あなたはinputValueでの親関数の引数として小道具nameを通過した後、ここに[key]がダイナミックキーと...this.state.inputValue,で状態オブジェクトを更新するために使用される

this.setState({ 
     inputValue: { 
      ...this.state.inputValue, 
      [key]: e.target.value 
     } 
     }) 

注意が広がっているような状態を更新することができ他のすべての値をinputValue状態に保つための演算子構文。

はやる ...何の説明についてはこの回答を参照してください。

What is the meaning of this syntax "{...x}" in Reactjs

DEMO

class App extends React.Component { 
 
    state = { 
 
     inputValue: {} 
 
    } 
 
    
 
    inputValue(e, key) { 
 
    console.log(key, e.target.value); 
 
     
 
     this.setState({ 
 
     inputValue: { 
 
      ...this.state.inputValue, 
 
      [key]: e.target.value 
 
     } 
 
     })  
 
    } 
 
    render() { 
 
     return (
 
      <div> 
 
       <InputField 
 
        name='source' 
 
        type='text' 
 
        input={(e, key) => this.inputValue(e, key)} 
 
        inputValue={this.state.inputValue['source'] || ''} /> 
 
       <InputField 
 
        name='text' 
 
        type='text' 
 
        input={(e, key) => this.inputValue(e, key)} 
 
        inputValue={this.state.inputValue['text'] || ''} /> 
 
      </div> 
 
     ) 
 
    } 
 
} 
 

 
class InputField extends React.Component { 
 
    render() { 
 
     return (
 
      <div> 
 
       <input type={this.props.type} value={this.props.inputValue} onChange ={(e) => this.props.input(e, this.props.name)}/> 
 
      </div> 
 
     ) 
 
    } 
 
} 
 

 
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="app"><div>

+0

ありがとうございます。それはまさに私が探していたものです。 –

関連する問題