javascript - 如何返回一个复杂的直接从 state 传递给 React 中的子组件
问题描述
我需要将一大段文本从我的父组件传递给我的子组件。我有一个带有状态的 Class 组件,我想将文本传递给模态。问题是,它是相当大的文本块。
我的状态
state={
iten:[
{
id: 1,
header: 'header text',
bigChunkForModal:
<div>
<p>pargaraph text1</P
<ul><li> List item 1</li></ul>
<p>pargaraph text2</P
<ul><li> List item 2</li></ul>
<p>pargaraph text3</P
<ul><li> List item 3</li></ul>
</div>,
modalHeader: 'Modal header
},
],
}:
我希望这一切从我的状态转移到我的模态
{item.map((item) => {
return(
<Modal
show={showModal === item.id}
classModal={'btn-offer'}
modalId={item.id}
modalHeader={item.modalHeader}
modalText={item.bigChunkForModal}
close={() => this.closeModal()}
/>
);
}
最后是我的模态。我有 3 个按钮,应该显示 3 个模式。这部分正在工作。好的
const ModalOverlay = ({
className,
modalHeader,
show,
modalId,
modalText,
classModal,
close,
}) => {
const content = (
<div
className={`Modal__Container ${className}`}
style={{
display: show ? 'inline' : 'none',
}}>
<div key={modalId} className={`Modal__Content ${className}`}>
<h2>{modalHeader}</h2>
<div>{modalText}</div>
<button className={`btn ${classModal}`} onClick={close}>
Zamknij
</button>
</div>
</div>
);
return ReactDOM.createPortal(
content,
document.getElementById('modal-portal')
);
};
我唯一需要做的就是状态部分。有什么建议吗?
解决方案
您虽然可以工作,但您可以稍微不同地构建组件 API 以使其更加明显。
<Modal show = {show} header="Demo Modal" onClose={}>
<div>This will be available in the modal component as props.childrent {text}</div>
</Modal>
模态按钮将在 Modal 组件中抽象出来。通过这样做,您可以将模态内容作为模态定义的一部分传递,并且在模态组件内部,您可以获取子道具并在适当的位置进行渲染。我只给出了占位符。{} 值可以是动态的。
注意:如果您可以将当前的 MVP 工作代码放在 jsbin/codepen 中,我可以更新修改后的结构以避免填充 HTML 的状态。
推荐阅读
- c++ - 在 for 循环中使用 erase() 仅擦除第一行
- laravel - 在 Laravel 项目中同步标签时出错
- java - 使用spring cloud和spring boot 2.0.1时maven依赖不兼容
- angular5 - 角度为 5 的 aws-sdk sendemail。请求的资源上不存在“Access-Control-Allow-Origin”标头
- kotlin - 类型不匹配:推断类型为 String 但应为 Int
- c# - 我正在尝试为私有方法创建单元测试
- java - JRadioButton 无法转换为 ButtonModel
- c# - XDocument 加载多个 XML
- javascript - 匹配最小可能组的正则表达式
- php - 每个逗号内的php文本解析