Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在React中,如何基于传入的道具动态渲染组件?_Javascript_Reactjs - Fatal编程技术网

Javascript 在React中,如何基于传入的道具动态渲染组件?

Javascript 在React中,如何基于传入的道具动态渲染组件?,javascript,reactjs,Javascript,Reactjs,我有一个要渲染的组件,该组件将根据传入的道具进行不同的渲染: const Label = ({ data, attribute, style, link }) => ( <Link to={link} style={style}>{data ? `${data[attribute]}` : ''}</Link> ); 我会这样做: const Label = ({ data, attribute, style, link }) => { if (li

我有一个要渲染的组件,该组件将根据传入的道具进行不同的渲染:

const Label = ({ data, attribute, style, link }) => (
  <Link to={link} style={style}>{data ? `${data[attribute]}` : ''}</Link>
);

我会这样做:

const Label = ({ data, attribute, style, link }) => {
  if (link) {
    return (
      <Link to={link} style={style}>{data ? `${data[attribute]}` : ''}</Link>
    );
  }
  // ...
};
constlabel=({data,attribute,style,link})=>{
如果(链接){
返回(
{data?`${data[属性]}`:'''}
);
}
// ...
};

您应该能够安全地通过未定义的
样式
道具

您可以创建一个道具,专门用于
链接
组件,并相应地定义道具类型。在下面的示例中,道具
linkProps
分布在
Link
组件中

//一个模拟,只是为了说明我的观点。。。
constlink=props=>();
常量标签=({data,attribute,linkProps={}})=>(
{data?`${data[属性]}`:'''}
);
Label.propTypes={
数据:React.PropTypes.object.isRequired,
属性:React.PropTypes.string.isRequired,
linkProps:React.PropTypes.shape({
样式:React.PropTypes.object,
至:React.PropTypes.string
})
};
类Main扩展了React.Component{
render(){
const data={label:'Hello!'};
常量linkProps={
样式:{fontWeight:'bold'}
};
返回(
)
}
}
ReactDOM.render(,document.getElementById('main'))

Aha!没有隐含的回报——是的,这是有道理的,谢谢:)
const Label = ({ data, attribute, style, link }) => {
  if (link) {
    return (
      <Link to={link} style={style}>{data ? `${data[attribute]}` : ''}</Link>
    );
  }
  // ...
};