我正在更改道具的类属性,然后我希望组件使用新类重新渲染但不起作用。我已阅读有关shouldComponentUpdate方法,但该方法永远不会被调用。道具变化时反应不会重新渲染组件
var ReactDOM = require('react-dom');
var React = require('react');
class Button extends React.Component {
constructor(props) {
super(props);
console.log("BUTTON")
console.log(props);
var options = props.options;
}
componentWillMount() {
var defaultFeatureOptionId = this.props.feature.DefaultFeatureOptionId;
this.props.options.forEach((option) => {
var classes = "";
if (option.Description.length > 10) {
classes = "option-button big-button hidden";
} else {
classes = "option-button small-button hidden";
}
if (option.Id === defaultFeatureOptionId) {
classes = classes.replace("hidden", " selected");
option.selected = true;
}
option.class = classes;
});
}
shouldComponentUpdate(props) {
console.log("UPDATE");
}
toggleDropdown(option, options) {
console.log(option);
console.log(options)
option.selected = !option.selected;
options.forEach((opt) => {
if (option.Id !== opt.Id) {
opt.class = opt.class.replace("hidden", "");
}
else if(option.Id === opt.Id && option.selected) {
opt.class = opt.class.replace("", "selected");
}
});
}
render() {
if (this.props.options) {
return (<div> {
this.props.options.map((option) => {
return <div className={ option.class } key={option.Id}>
<div> {option.Description}</div>
<img className="option-image" src={option.ImageUrl}></img>
<i className="fa fa-chevron-down" aria-hidden="true" onClick={() => this.toggleDropdown(option, this.props.options) }></i>
</div>
})
}
</div>
)
}
else {
return <div>No options defined</div>
}
}
}
module.exports = Button;
我已经阅读了很多关于shouldComponentUpdate和componentWillReceiveProps不同的事情,但似乎有别的东西我失踪。
触发时才会调用我读了一篇博客“只有组件的状态发生了变化才能触发重新呈现,状态可以从道具更改或直接setState更改中更改,组件获取更新的状态,React决定是否应该重新渲染,渲染组件“。道具和状态都会触发状态变化 –