将输入字段中的数据传递到变量而不提交

时间:2017-02-05 14:51:01

标签: reactjs jsx

试着让我的头脑反应过来。我想从输入字段中获取数据并将其传递给变量(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'))

2 个答案:

答案 0 :(得分:2)

为此,您需要在App组件中使用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

答案 1 :(得分: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