我在反应中创造了一个可以扩展崩溃功能的手风琴。 渲染:
<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>
但每次手风琴扩展/折叠,子组件都是未安装的。因此,他们失去了自己的任何数据/状态,我必须保持一切 当展开崩溃时也不会重新渲染。
不应该重新渲染子组件,而不是卸载并在崩溃扩展时再次安装。有没有办法实现同样的目标。 我不想保持每个孩子Compoent的状态
@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>
}
MyChildComponent:
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'。哪个有效。但是当我们崩溃然后再次展开时,标签会重置为“初始字符串”
答案 0 :(得分:0)
包含的代码有一些错误,无法编译。我删除了一些不需要重现此错误的代码,现在在codepen处有一个可行的解决方案。代码也包括在下面,我使用React.createClass而不是扩展React.Component,但你当然不必。:
const Accordion = React.createClass({
getInitialState: function () {
return { expanded: false }
},
_toggle: function () {
this.setState({
expanded: !this.state.expanded
});
},
render: function () {
return (
<div>
<div onClick={ this._toggle }>
<label className={ className } />
<label className="label"> { this.props.label } </label>
</div>
<div style={{
display: !!this.state.expanded ? "block" : "none"
}}>{ this.props.children }</div>
</div>
);
}
});
const MyChildComponent = React.createClass({
getInitialState: function () {
return { stateString: this.props.stringParentProp}
},
_changeLabel: function () {
this.setState(
{
stateString: this.state.stateString + "x"
})
},
render: function () {
return (
<div onClick={this._changeLabel}>
<label>{this.state.stateString}</label>
</div>
)
}
})
const Parent = () => {
return (
<Accordion label="Sample Accordion2" expanded={true} >
<MyChildComponent
sampleProp="aa"
stringParentProp="initial string"/>
<label>"Hello World3"</label>
</Accordion>
)
}
ReactDOM.render(<Parent/>, document.getElementById('container'))