React组件接收组件作为Props的灵活实现方案问询
如何创建可接收其他组件作为Props的React组件
原代码存在的问题
- import语句不能放在函数组件内部,必须置于文件最顶部
REACTCode的传递方式错误,不能直接将import语句作为props值- HTML标签未正确闭合(
<div>My Heading<div>缺少闭合标签)
修正后的基础实现
1. ScenarioComponent.js(优化命名,保持逻辑清晰)
function ScenarioComponent(props) { return ( <div> <h1>{props.title}</h1> <div className='row'> {props.htmlContent} </div> <div className='row'> {props.reactComponent} </div> </div> ); } export default ScenarioComponent;
2. SampleComponent.js(修正语法错误,正确传递组件)
确保import在文件顶部,正确传递HTML内容和React组件:
import ScenarioComponent from './components/ScenarioComponent'; // 自定义一个复杂组件示例 function ComplexCustomComponent() { return ( <div> <h3>这是一个复杂的自定义组件</h3> <p>包含多段子元素与业务逻辑</p> <button>操作按钮</button> </div> ); } function SampleComponent(props) { return ( <div> <ScenarioComponent title="My New Component" htmlContent={<div>My Heading</div>} reactComponent={<ComplexCustomComponent />} /> </div> ); } export default SampleComponent;
更灵活的实现方案
方式1:多插槽模式(适配多区域传递不同组件)
通过定义多个props插槽,实现不同区域的组件自定义:
// ScenarioComponent.js function ScenarioComponent(props) { return ( <div> <h1>{props.title}</h1> <div className='row top-area'>{props.topContent}</div> <div className='row middle-area'>{props.middleContent}</div> <div className='row bottom-area'>{props.bottomContent}</div> </div> ); } // 使用示例 <ScenarioComponent title="Multi-slot Component" topContent={<div>顶部静态内容</div>} middleContent={<ComplexCustomComponent />} bottomContent={<AnotherCustomComponent />} />
方式2:传递组件类/函数(支持内部动态控制)
如果需要在父组件内部控制子组件的props或渲染逻辑,可以直接传递组件本身而非实例:
// ScenarioComponent.js function ScenarioComponent(props) { const TargetComponent = props.targetComponent; return ( <div> <h1>{props.title}</h1> <div className='row'> {/* 内部动态传递props */} <TargetComponent customProp="父组件传入的属性" /> </div> </div> ); } // 使用示例 <ScenarioComponent title="Dynamic Component" targetComponent={ComplexCustomComponent} />
内容的提问来源于stack exchange,提问作者Anushweta
相关产品推荐
相关产品推荐

