我正在尝试根据我发送给组件的专利人动态设置类。不知何故,我会遇到"无法读取未定义的属性"状态"的错误。我想当我尝试将状态的班级设置为班级时,这不存在吗?在使用组件的渲染中,我是否必须重新启动它?
var ReactDOM = require('react-dom');
var React = require('react');
class Button extends React.Component {
constructor(props) {
super(props);
console.log("BUTTON")
console.log(props);
this.state = {
class: "small-button"
};
props.options.map(function (option) {
if (option.Description > 10) {
this.setState({
class: "big-button"
});
}
});
console.log("STATE: " + this.state.class);
}
render() {
if (this.props.options) {
return (<div> {
this.props.options.map(function (option) {
return <div className={ this.state.class === 'big-button' ? 'option-button big-button' : 'option-button small-button'} key={option.Id}> {option.Description}</div>
})
}
</div>
)
} else {
return <div>No options defined</div>
}
}
}
module.exports = Button;
这是一个绑定的问题,您需要bind
使用this
关键字(正确的上下文(的函数。
使用此:
render() {
if (this.props.options) {
return (<div> {
this.props.options.map((option) => {
return <div className={ this.state.class === 'big-button' ? 'option-button big-button' : 'option-button small-button'} key={option.Id}> {option.Description}</div>
})
}
</div> )
} else {
return <div>No options defined</div>
}
}
检查此答案以获取有关箭头功能的更多详细信息,此关键字
一个建议:不要将逻辑放入constructor
中,并且也不要使用setState
,也请使用生命周期方法。将该逻辑放入componentDidMount
方法或componentWillMount
方法中。
这样:
class Button extends React.Component {
constructor(props) {
super(props);
this.state = {
class: "small-button"
};
}
componentDidMount(){
this.props.options.forEach((option) => {
if (option.Description > 10) {
this.setState({
class: "big-button"
});
}
});
}
render() {
if (this.props.options) {
return (
<div>
{
this.props.options.map((option) => {
return <div className={ this.state.class === 'big-button' ? 'option-button big-button' : 'option-button small-button'} key={option.Id}> {option.Description}</div>
})
}
</div>
)
}else{
return <div>No options defined</div>
}
}
}