【发布时间】:2017-05-09 06:23:45
【问题描述】:
我正在更改我的道具的类属性,然后我希望组件使用新类重新呈现,但这不起作用。我已经阅读了有关 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 决定它是否应该重新渲染组件。“props 和 state 都会触发状态变化
标签: reactjs components