子どもが内部で登録できる親コンポーネントを持っているので、私はこのデータをどこか他の場所で使うことができます(例えば、メニューを生成する)。次のようにReact - 子と親の関係が小道
現在、私のコードは次のとおりです。
const app = document.getElementById('app');
class Children extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.props.add(this.props.name);
}
render() {
return (
<div>Children</div>
)
}
}
class Items extends React.Component {
render() {
return (
<nav>
{this.props.content}
</nav>
)
}
}
class Parent extends React.Component {
constructor() {
super();
this.state = {
sections: []
}
}
add(section) {
const currentSections = this.state.sections;
const id = section.replace(' ', '-').toLowerCase();
const obj = { name: section, id };
this.setState({
sections: currentSections.push(obj)
});
}
render() {
console.log(this.state.sections);
return (
<div>
<Items content={this.state.sections} />
<Children add={this.add.bind(this)} name="Section 1" />
<Children add={this.add.bind(this)} name="Section 2" />
<Children add={this.add.bind(this)} name="Section 3" />
</div>
)
}
}
render(<Parent />, app);
私の問題は3
を返しthis.state.sections
、ですが、私はcomponentDidMount
で再度ログインしたときに、それが配列です。 どうすればいいですか?
わからない:これを緩和するために
、あなたはすべての3つが順次追加されることが保証されます
setState
を呼び出す別の方法を使用することができます配列。あなたの問題は何ですか? –問題は 'state.sections'は' render'ではなく、 'componentDidMount'の後の配列です。 'render'で' console.log(this.state.sections) 'を実行すると' 3'が得られます。 –
ああ、私は参照してください。参考のためにjsbinを追加しました –