【问题标题】:How to convert React.DOM elements to JSX?如何将 React.DOM 元素转换为 JSX?
【发布时间】:2018-01-15 05:33:08
【问题描述】:

说到 React JSX 代码标准: 我将如何着手将以下代码重构为 JSX?

const ListContainer = (props) => React.DOM.table({ className: 'list-container' }, [
    React.DOM.thead({ key: 'firstName' }, React.DOM.tr({}, [
        React.DOM.th({ key: 'lastName' }, null, 'headshot'),
        React.DOM.th({ key: 'id' }, null, 'First Name'),
        React.DOM.th({ key: 'last-h' }, null, 'Last Name')
    ])),
    React.DOM.tbody({ key: 'tbody' }, props.personList.map((person, i) =>
        React.createElement(ListRow, { key: `person-${i}`, person })))
]);

【问题讨论】:

    标签: javascript reactjs ecmascript-6 redux react-dom


    【解决方案1】:

    查看演示:CodePen

    翻译如下:

    const ListContainer = props => (
        <table className="list-container">
            <thead>
                <th>
                    headshot
                </th>
                <th>
                    First Name
                </th>
                <th>
                    Last Name
                </th>
            </thead>
            <tbody>
                {
                    props.personList.map((person, i) => {
                        return <ListRow key={`person-${i}`} person={person} />
                    })
                }
            </tbody>
        </table>
    );
    

    当然,对于上述内容,您需要使用 babel 转译器(如果您需要更多信息,请告诉我)。

    然后您可以在 JSX 中按如下方式使用您的 const:

    <ListContainer />
    

    【讨论】:

    • 嗨@sammysaglam 我对将两者结合起来感到困惑,换句话说,正确的语法是:React.DOM.th({ key: 'last-h' }, null, 'Last Name' ) + React.DOM.tbody({ key: 'tbody' }, props.personList.map((person, i) => React.createElement(ListRow, { key: person-${i}, person }))))
    • 所以,我将你的代码翻译成 JSX;但是,我不建议在 组件上使用 key 属性 => 原因是 React 在创建元素列表时使用 key 作为特殊的字符串属性(例如,使用上面的“map”方法) )。 “键帮助 React 识别哪些项目已更改、添加或删除。应为数组内的元素提供键以赋予元素稳定的身份”(facebook.github.io/react/docs/lists-and-keys.html#keys)。当然,“key”属性并没有什么坏处,但在上面是多余的。
    • @rimatla13 我在 (CodePen) 添加了一个演示 — [codepen.io/anon/pen/gxmPVv?editors=1111]
    • 这是有道理的@sammysaglam。非常感谢!
    猜你喜欢
    • 2018-12-20
    • 2021-09-28
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2021-06-14
    • 2020-11-13
    • 2016-11-08
    • 2010-10-12
    相关资源
    最近更新 更多