2017-02-05 42 views
-1

私の頭を反応させようとしています。私は、入力フィールドからデータを取り出し、変数(let)に渡して、別の文字列でhtmlに渡すことができます。これは「双方向の拘束力」でしょうか?誰かがこの作業の簡単な例を持っていますか?投稿しないで入力フィールドから変数にデータを渡す

http://codepen.io/IanHazelton/pen/ygEomV?editors=0110

let name="{name from input}"; 
let age="{age from input}"; 

class App extends React.Component { 
    render() { 
    return (
     <div className ="wrap"> 
      <h1 className="string">What's your name?</h1> 
      <input type="text" id="name" /> 
      <h1 className="string">How old are you?</h1> 
      <input type="text" id="age" /> 
      <h1 className="string">Hi {name}! How are you today? You're {age} years old.</h1> 
     </div> 
    ) 
    } 
} 

ReactDOM.render(<App/>, document.getElementById('Root')) 

答えて

1

あなたは部品のstateを利用する必要があります。私はあなたの他の入力に同じことを行うことができ、name財産で動作するようにあなたのペンを変更:そのために

class App extends React.Component { 

    constructor(props) { 
    super(props); 

    this.state = { 
     value: '' 
    }; 
    } 

    handleNameOnChange(e) { 
    this.setState({ 
     name: e.target.value 
    }); 
    } 

    render() { 
    return ( 
     <div className="wrap"> 
      <h1 className="string">What's your name?</h1> 
      <input type="text" id="name" value={this.state.name} onChange={ (e) => this.handleNameOnChange(e) } /> 
      <h1 className="string">How old are you?</h1> 
      <input type="text" id="age" /> 
      <h1 className="string">Hi {this.state.name}! How are you today? You're {age} years old.</h1> 
     </div> 
    ) 

    } 
} 

CodePen

+0

Works!フレンドリーで有益で効果的な返信をありがとう! – chilledMonkeyBrain

2

あなたがアプリケーションコンポーネントでstateを使用する必要があり、ユーザーがいずれかを提供するたびにコンセプトがありますfieldsで入力、state変数にそれらの値を格納し、そして、あなたはstate値、再びReactますrender全体componentの変更を加えるたび、これを試してみてください。

class App extends React.Component { 
    constructor(){ 
    super(); 
    this.state={name: '', age: ''} 
    } 
    render() { 
    return (
     <div className ="wrap"> 
      <h1 className="string">What's your name?</h1> 
      <input value={this.state.name} type="text" id="name" onChange={(e)=>{this.setState({name: e.target.value})}}/> 
      <h1 className="string">How old are you?</h1> 
      <input value={this.state.age} onChange={(e)=>{this.setState({age: e.target.value})}} type="text" id="age" /> 
      <h1 className="string">Hi {this.state.name}! How are you today? You're {this.state.age} years old.</h1> 
     </div> 
    ) 
    } 
} 

ReactDOM.render(<App/>, document.getElementById('Root')) 

実際の例を確認してください。http://codepen.io/anon/pen/egKyvJ?editors=0110

+0

作品!フレンドリーで有益で効果的な返信をありがとう! – chilledMonkeyBrain

関連する問題