【问题标题】:React - passing unique React components as propsReact - 将独特的 React 组件作为道具传递
【发布时间】:2018-03-15 20:42:03
【问题描述】:

我有兴趣了解将 React 组件作为道具传递时的最佳实践,尤其是在传递独特组件时。

一些示例伪代码

import IconOne;
import IconTwo;
import IconThree;

const arr = [
    { icon: IconOne },
    { icon: IconTwo },
    { icon: IconThree },
]

render() {
    return (
        {arr.map(item => (
            <Container icon={item.icon} />
        ))}
    )
}

我拥有的图标是独一无二的,因为它们呈现的是 svg 图标。这样做是不好的做法吗?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您的示例没有任何问题,但渲染功能目前是一种趋势。大概是为了通过道具传递和惰性评估来获得额外的控制级别。另外:don't forget to pass keys.

    import IconOne;
    import IconTwo;
    import IconThree;
    
    const arr = [
        { title: 'one', render: props => <IconOne {...props} /> },
        { title: 'two', render: props => <IconTwo {...props} /> },
        { title: 'three', render: props> <IconThree {...props} /> },
    ]
    
    render() {
        const foo = this.props.foo
        return arr.map( ({ title, render }) => 
            <Container key={title} renderIcon={() => render(foo)} />
        )
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-01
      • 2017-09-06
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      • 2023-03-12
      • 2022-01-24
      相关资源
      最近更新 更多