2016-09-20 51 views
1

http://jsfiddle.net/adamchenwei/3rt0930z/20/ReactJS不能引用状态下创建

我只是想建立一个例子来学习状态列表中是如何工作的。

我打算做的是允许在列表中重复的特定值,通过使用状态来更改列表中的所有项目。例如,在这种情况下,我想在运行onClick的changeName时将所有列表项的名称更改为'lalala'。

但是我有这样的警告(在小提琴版本11的问题,在15版本解决) enter image description here

上解决它来实现上述目的的任何帮助吗?

实际代码

var items = [ 
    { name: 'Believe In Allah', link: 'https://www.quran.com' }, 
    { name: 'Prayer', link: 'https://www.quran.com' }, 
    { name: 'Zakat', link: 'https://www.quran.com' }, 
    { name: 'Fasting', link: 'https://www.quran.com' }, 
    { name: 'Hajj', link: 'https://www.quran.com' }, 
]; 

var ItemModule = React.createClass({ 
    getInitialState: function() { 
     return { newName: this.props.name } 
    }, 
    changeName() { 
    console.log('changed name'); 
    this.setState({ newName: 'lalala' }); 
    }, 
    render() { 
    //<!-- <a className='button' href={this.props.link}>{this.props.name}</a> --> 
    return (
     <li onClick={this.changeName}> 

     {this.state.newName} 
     </li> 
    ); 
    } 
}); 

var RepeatModule = React.createClass({ 
    getInitialState: function() { 
     return { items: [] } 
    }, 
    render: function() { 

     var listItems = this.props.items.map(function(item) { 
      return (
       <div> 
      <ItemModule 
      key={item.name} 
      name={item.name} /> 
     </div> 
      ); 
     }); 

     return (
      <div className='pure-menu'> 
       <h3>Islam Pillars</h3> 
       <ul> 
        {listItems} 
       </ul> 
      </div> 
     ); 
    } 
}); 

ReactDOM.render(<RepeatModule items={items} />,     
    document.getElementById('react-content')); 

-UPDATE- 小提琴版本16

更新FIDLE,现在是关键问题,另外,的onClick没有为所有的列表项更新值。我做错了吗?

-UPDATE- 小提琴版本20

现在唯一的问题是change all the list item's name to 'lalala' when I run changeName of onClick.

+1

我想你打算做'onClick = {this.changeName}' – Neal

回答

4

移除

onClick={this.changeName()}括号,

所以

onClick={this.changeName}

要调用函数的onClick,但你调用它的渲染方式

+0

hi @Davidlrnt你知道更新的issu è? – Ezeewei

+0

你需要将一个唯一的数字传递给key,通常的做法是通过当前迭代的索引 – StackOverMySoul

+0

我打开了我的小提琴。同样的事情,我添加索引后。思想? – Ezeewei

2

我想你的意思做onClick={this.changeName}

在你拥有了它您呼叫的changeName功能的方式在渲染而不是点击。