我正在尝试更改图像源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'));
儿童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>
)
}
});
据我所知,我没有在代码中使用任何非法状态转换或setState()
方法。请帮我解决这个问题。提前谢谢。
答案 0 :(得分:5)
写作时
onClick = {this.handleBackgroundChange(0)}
你直接执行该功能而不是提供他的参考,试试这个
onClick = {this.handleBackgroundChange.bind(this, 0)}
答案 1 :(得分:0)
我也遇到了这个问题,我做了(从同事的代码中窃取),例如const handleBackgroundChange = () => this.handleBackgroundChange(0)
而不需要bind()
。