gpt4 book ai didi

javascript - 在 React.js 中触发子项重新渲染

转载 作者:IT王子 更新时间:2023-10-29 03:00:31 24 4
gpt4 key购买 nike

父组件(在我的示例中为 MyList)组件通过子组件(MyComponent)呈现数组。 Parent 决定更改数组中的属性,React 触发 child 重新渲染的方式是什么?

我想出的只是 this.setState({}); 在调整数据后在 Parent 中。这是触发更新的 hack 方式还是 React 方式?

JS fiddle : https://jsfiddle.net/69z2wepo/7601/

var items = [
{id: 1, highlighted: false, text: "item1"},
{id: 2, highlighted: true, text: "item2"},
{id: 3, highlighted: false, text: "item3"},
];

var MyComponent = React.createClass({
render: function() {
return <div className={this.props.highlighted ? 'light-it-up' : ''}>{this.props.text}</div>;
}
});

var MyList = React.createClass({
toggleHighlight: function() {
this.props.items.forEach(function(v){
v.highlighted = !v.highlighted;
});

// Children must re-render
// IS THIS CORRECT?
this.setState({});
},

render: function() {
return <div>
<button onClick={this.toggleHighlight}>Toggle highlight</button>
{this.props.items.map(function(item) {
return <MyComponent key={item.id} text={item.text} highlighted={item.highlighted}/>;
})}
</div>;
}
});

React.render(<MyList items={items}/>, document.getElementById('container'));

最佳答案

这里的问题是您将状态存储在 this.props 而不是 this.state 中。由于此组件正在改变 items,因此 items 是状态并且应该存储在 this.state 中。 (这里是 good article on props vs. state。)这解决了您的渲染问题,因为当您更新 items 时,您将调用 setState,这将自动触发重新渲染。

下面是你的组件使用 state 而不是 props 时的样子:

var MyList = React.createClass({
getInitialState: function() {
return { items: this.props.initialItems };
},

toggleHighlight: function() {
var newItems = this.state.items.map(function (item) {
item.highlighted = !item.highlighted;
return item;
});

this.setState({ items: newItems });
},

render: function() {
return (
<div>
<button onClick={this.toggleHighlight}>Toggle highlight</button>
{ this.state.items.map(function(item) {
return <MyComponent key={item.id} text={item.text}
highlighted={item.highlighted}/>;
}) }
</div>
);
}
});

React.render( <MyList initialItems={initialItems}/>,
document.getElementById('container') );

请注意,我将 items 属性重命名为 initialItems,因为它清楚地表明 MyList 会改变它。这是 recommended by the documentation .

你可以在这里看到更新的 fiddle :https://jsfiddle.net/kxrf5329/

关于javascript - 在 React.js 中触发子项重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30034265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com