【发布时间】:2016-09-16 03:32:07
【问题描述】:
我在 react 中创建了一个具有扩展折叠功能的手风琴。 渲染:
<div>
<div>
<label className="label">
{ this.props.label }
</label>
</div>
<div style={{ display: !!this.state.expanded ? "block" : "none" }}>
{ this.props.children } </div>
</div>
我这样称呼它:
<Accordion>
<MyComponent1/>
<MyComponent2/>
<MyComponent3/>
</Accordion>
但每次手风琴展开/折叠时,子组件都会被卸载。因此,他们会丢失自己的任何数据/状态,我必须保留所有内容 发生展开折叠时也不会重新渲染。
当发生折叠扩展时,子组件不应该只是重新渲染而不是卸载和重新安装。有没有办法达到同样的效果。 我不想保留每个子组件的状态
@Drew Schuster:完整代码-
导出类 Accordion 扩展 React.Component {
constructor(props) {
super(props);
this.state = {
expanded: false
}
}
public render(): JSX.Element {
let className = My_String_Util.format("chevron-", this.state.expanded ? "down" : "right");
return (
<div>
<div onClick={ this._toggle }>
<label className={ className } />
<label className="label"> { this.props.label } </label>
</div>
<If condition={ this.state.expanded }>
<div style={{
display: !!this.state.expanded ? "block" : "none"
}}>{ this.props.children }</div>
</If>
</div>
);
}
private _toggle = (): void => {
this.setState({
expanded: !this.state.expanded
});
}
}
父组件:
render(): JSX.Element {
<Accordion label="Sample Accordion2" expanded={true} >
<MyChildComponent
sampleProp={"aa"}
stringParentProp={"initial string"}/>
<label>"Hello World3"</label>
</Accordion>
}
我的孩子组件:
constructor(props) {
this.state = {
stateString = this.props.stringParentProp
}
}
render(): JSX.Element {
<div onClick={this._changeLabel}>
<label>this.state.stateString</label>
</div>
}
private _changeLabel() {
this.setState = {
stateString = this.state.stateString + "x";
}
}
这应该在我们每次点击子组件时添加'x'到它的标签。哪个有效。但是当我们折叠然后再次展开时,标签会重置为“初始字符串”
【问题讨论】:
-
你能发布更多代码吗?到目前为止,您提交的代码应该可以按预期工作,查看整个手风琴组件以及调用它的位置可能会更有帮助。
-
@DrewSchuster 添加了有问题的代码