从对象更新onChange React.JS映射的输入

时间:2016-10-16 04:42:27

标签: javascript reactjs

我正在尝试将对象映射到可以更新onChange的输入。一切都有效,除了组件永远不会在this.setState()之后更新。

var ItemModal = React.createClass({
  getInitialState: function(){
    return {
      title: "",
      cooktime: "",
      ingredients: [],
      instructions: ""
    }
   },  

  componentWillReceiveProps: function(nextProps) {
     this.setState({
       title: nextProps.inputVal.title,
       cooktime: nextProps.inputVal.cooktime,
       ingredients: nextProps.inputVal.ingredients,
       instructions: nextProps.inputVal.instructions
     });
},

  handleChange: function(event){
    var change = {};
    console.log(event.target.id + " " + event.target.value)
    change[event.target.id] = event.target.value;
    console.log(change);
    this.setState(change);
},

  render: function (){
    var handleChange = this.handleChange;
    var inputVal = this.props.inputVal;
    return (
      <div id="itemModal">
        <div id="modalContent">
           {
            Object.keys(this.props.inputVal).map(function(curr){
              return <input id={curr} placeholder= "Recipe Name Here!" type="text" value= {inputVal[curr]|| ""}  onChange = {handleChange.bind(this)}/>   
        })
       } 
        </div>
       </div>  
     );
   }
 });

link to code

转到我提到的ItemModal代码就在那里。

1 个答案:

答案 0 :(得分:0)

handleChange在课堂内。因此,您需要使用this在类中访问它。如下更改render

render: function (){
    var handleChange = this.handleChange;
    var inputVal = this.props.inputVal;
    var _this = this;
    return (
      <div id="itemModal">
        <div id="modalContent">
           {
            Object.keys(this.props.inputVal).map(function(curr){
              return <input id={curr} placeholder= "Recipe Name Here!" type="text" value= {inputVal[curr]|| ""}  onChange = {_this.handleChange.bind(_this)}/>   
        })
       } 
        </div>
       </div>  
     );
   }