高级 React.js
文本组件
今天我们学习了 Reactjs 中的一些新知识和高级知识,我们都知道在 Reactjs 中 props 用于与其他组件进行通信。
现在我们来学习一些不同的东西,即 React 中的复合组件,它使用一些顶级 API。
1.React.Children.map
2.React.cloneElement()
我们的最终输出应该如下图所示。
手风琴组件代码
<Accordion>
<Heading>Heading 1</Heading>
<Text>
“You've gotta dance like there's nobody watching, Love like you'll
never be hurt, Sing like there's nobody listening, And live like it's
heaven on earth.” ― William W. Purkey
</Text>
<Heading>Heading 2</Heading>
<Text>
“Don’t walk in front of me… I may not follow Don’t walk behind me… I
may not lead Walk beside me… just be my friend” ― Albert Camus
</Text>
<Heading>Heading 3</Heading>
<Text>
“Darkness cannot drive out darkness: only light can do that. Hate
cannot drive out hate: only love can do that.” ― Martin Luther King
Jr., A Testament of Hope: The Essential Writings and Speeches
</Text>
<Heading>Heading 4</Heading>
<Text>
Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam.
Integer ut neque. Vivamus nisi metus, molestie vel, gravida in,
condimentum sit amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi.
Proin viverra leo ut odio. Curabitur malesuada. Vestibulum a velit eu
ante scelerisque vulputate.
</Text>
<Heading>Heading 5</Heading>
<Text>
“I believe that everything happens for a reason. People change so that
you can learn to let go, things go wrong so that you appreciate them
when they're right, you believe lies so you eventually learn to trust
no one but yourself, and sometimes good things fall apart so better
things can fall together.” ― Marilyn Monroe
</Text>
</Accordion>
现在让我们进入上述代码中的逻辑,Accordion 组件包含不同类型的子组件,例如标题、文本。
手风琴组件的实现。
class Accordion extends React.Component {
state = {
active: -1
};
onShow = i => {
this.setState({
active: i
});
};
render() {
const children = React.Children.map(this.props.children, (child, i) => {
return React.cloneElement(child, {
heading: this.state.active === i,
text: this.state.active + 1 === i,
onShow: () => this.onShow(i)
});
});
return <div className="accordion">{children}</div>;
}
}
上面的代码所做的不是返回子项,而是使用 React.Children.map 映射子项,并通过将某些状态传递给子项来克隆子项,这意味着我们将状态传递给子项。
标题组件。
class Heading extends React. Component {
render() {
const { heading, onShow, children } = this.props;
return (
<h2 className={heading ? "active" : "normal"} onClick={onShow}>
{children}
</h2>
);
}
}
文本组件
class Text extends React.Component {
contentBox = () => {
if (!this.props.text) {
return null;
} else {
return (
<div className="content-box">
<p className="text">{this.props.children}</p>
</div>
);
}
};
render() {
return this.contentBox();
}
}
其他示例
您是否注意到文本或标题组件内不存在任何状态。
希望你们喜欢....