reactjs - 强制组件更新更改
问题描述
我试图让这个 componentFunction 使用发生 changeValue 的状态更改的新数据字段重新渲染,但我不知道我哪里出错了。
class Classname extends React.Component {
constructor() {
super();
this.state = {
value: "OriginalString",
};
}
changeValue = (newString) => {
this.setState({ value: newString });
this.forceUpdate();
};
componentFunction = () => {
return (
<div>
<component data={this.state.value} />
</div>
);
};
render() {
return (
<div>
<button
onClick={() => {
this.changeValue("updatedString");
}}
>
Update
</button>
<div className="control-section">
<DashboardLayoutComponent
id="dashboard_default"
columns={5}
cellSpacing={this.cellSpacing}
allowResizing={false}
resizeStop={this.onPanelResize.bind(this)}
>
<PanelsDirective>
<PanelDirective
sizeX={5}
sizeY={2}
row={0}
col={0}
content={this.componentFunction}
/>
</PanelsDirective>
</DashboardLayoutComponent>
</div>
</div>
);
}
}
ReactDOM.render(<Classname />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
解决方案
问题
this.state.value
这里的问题是in的陈旧外壳componentFunction
。
解决方案
据我所知,content
propPanelDirective
期望任何返回或解析为有效 JSX ( JSX attribute
) 的东西。提供内容的函数回调、React 组件或 JSX 文字都可以工作。
回调以重新封闭更新的状态。转换为一个 curried 函数,该函数可以在渲染组件时包含当前状态。附加回调时,您调用第一个函数并传递状态值,返回的函数
PanelDirective
将在调用内容值时使用。componentFunction = (data) => () => ( <div> <component data={data} /> </div> );
...
<PanelDirective sizeX={5} sizeY={2} row={0} col={0} content={this.componentFunction(this.state.value)} />
反应组件。转换
componentFucntion
为 React 组件并通过。ComponentFunction = ({ data }) => ( <div> <component data={data} /> </div> );
...
<PanelDirective sizeX={5} sizeY={2} row={0} col={0} content={<ComponentFunction data={this.state.value} />} />
JSX 字面量
<PanelDirective sizeX={5} sizeY={2} row={0} col={0} content={ <div> <component data={this.state.value} /> </div> } />
此外,如果不明显,您应该删除处理程序中的this.forceUpdate();
调用changeValue
。React 状态更新足以触发组件重新渲染。