Akh*_*l P 2 javascript reactjs
我试图改变图像源url from it's child component. If they clicks on button1 index 0 of backgroundImages阵列`将是图像源.button2将是索引1,按钮3将是索引2.
但它显示setstate在现有状态转换期间无法更新.
下面我附上代码.
App.jsx
var React = require('react');
var ReactDOM = require('react-dom');
var ChildComponent = require('./child-component.jsx');
var Hello = React.createClass({
getInitialState: function(){
return{
backgroundImage: 'https://images.unsplash.com/photo-1464013778555-8e723c2f01f8?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&s=4b2c415f63f63afa66a347f993351bee'
};
},
handleBackgroundChange: function(imageIndex) {
this.setState({
backgroundImage: this.backgrounds[imageIndex]
});
},
backgrounds: [
'https://images.unsplash.com/photo-1464013778555-8e723c2f01f8?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&s=4b2c415f63f63afa66a347f993351bee',
'https://images.unsplash.com/photo-1463595373836-6e0b0a8ee322?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&s=69a198dc9bfba968b5deb20c04cec8c9',
'https://images.unsplash.com/photo-1462819067004-905a72ea3996?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&s=4832f28a526c7a3538a887b8fbbfe897'
],
render: function() {
return(
<div>
<img src={this.state.backgroundImage} height="400px" width="400px"/>
<ChildComponent handleBackgroundChange = {this.handleBackgroundChange}/>
</div>
);
}
});
var element = React.createElement(Hello, {});
ReactDOM.render(element, document.querySelector('.container'));
Run Code Online (Sandbox Code Playgroud)
儿童component.jsx
var React = require('react');
module.exports = React.createClass({
handleBackgroundChange: function(imageIndex){
this.props.handleBackgroundChange(imageIndex);
},
render: function(){
return(
<div>
<button className="btn btn-primary" onClick = {this.handleBackgroundChange(0)}>Image 1</button>
<button className="btn btn-primary" onClick = {this.handleBackgroundChange(1)}>Image 2</button>
<button className="btn btn-primary" onClick = {this.handleBackgroundChange(2)}>Image 3</button>
</div>
)
}
});
Run Code Online (Sandbox Code Playgroud)
据我所知,我没有setState()在代码中使用任何非法的状态转换或方法.请帮我解决这个问题.提前致谢.
当你写作
onClick = {this.handleBackgroundChange(0)}
Run Code Online (Sandbox Code Playgroud)
你直接执行函数而不是给出他的引用,试试这样
onClick = {this.handleBackgroundChange.bind(this, 0)}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
942 次 |
| 最近记录: |