简体   繁体   English

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

[英]inputs mapped from object update onChange React.JS

I am trying to map out an object into inputs that can be updated onChange. 我试图将一个对象映射到可以在onChange上更新的输入中。 everything works except the component never updates after this.setState(). 一切正常,除了组件在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 链接到代码

goto ItemModal code I am mentioning is in there. 我要提到的goto ItemModal代码在其中。

The handleChange is inside a class. handleChange在一个类中。 So, you need to use this to access it within the class. 所以,你需要使用this该类中访问它。 Change your render as follows. 如下更改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>  
     );
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM