最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass multiple props to an element created by React.createElement? - Stack Overflow

programmeradmin2浏览0评论

React.createElement( type, [props], [...children] )

as the react documentation said. But somehow it's not working for me with multiple props. I tried to pass an array of key-value objects, pass a container object with key-values, but nothing isn't worked. Let me show how I tried it:

//input.js
const Input = ({name, elementProps}) => {
    const { element, props } = elementProps;
    return React.createElement(element, props)
}

export default Input;
//props from
{
    name: "msg",
    element: "textarea",
    props: [
        {placeholder: "Message"},
        {rows: "4"},
        {cols: "50"},
    ]
}
//rendered by method
const { name, ...elementProps } = objectAbove;
return <Input name={name} elementProps={elementProps} />

What's the required syntax to pass multiple props?

React.createElement( type, [props], [...children] )

as the react documentation said. But somehow it's not working for me with multiple props. I tried to pass an array of key-value objects, pass a container object with key-values, but nothing isn't worked. Let me show how I tried it:

//input.js
const Input = ({name, elementProps}) => {
    const { element, props } = elementProps;
    return React.createElement(element, props)
}

export default Input;
//props from
{
    name: "msg",
    element: "textarea",
    props: [
        {placeholder: "Message"},
        {rows: "4"},
        {cols: "50"},
    ]
}
//rendered by method
const { name, ...elementProps } = objectAbove;
return <Input name={name} elementProps={elementProps} />

What's the required syntax to pass multiple props?

Share Improve this question edited Oct 29, 2018 at 9:37 T.J. Crowder 1.1m200 gold badges2k silver badges2k bronze badges asked Oct 29, 2018 at 9:31 Gergő HorváthGergő Horváth 3,7255 gold badges42 silver badges84 bronze badges 1
  • 5 [props] in the documentation React.createElement( type, [props], [...children] ) just means that it's optional, not that it is an array. Your props should be an object instead. { placeholder: "Message", rows: "4", cols: "50"} – Tholle Commented Oct 29, 2018 at 9:35
Add a ment  | 

1 Answer 1

Reset to default 6

props should be a non-array object, not an array. The props array you're creating looks like it could easily be a single object rather than an array of objects. Instead of:

props: [
    {placeholder: "Message"},
    {rows: "4"},
    {cols: "50"},
]

perhaps

props: {
    placeholder: "Message",
    rows: "4",
    cols: "50"
}

As Tholle points out in a ment, the [] shown in the syntax in the documentation:

React.createElement( type, [props], [...children] )

...is meant to show that props is optional, not that it's an array.

发布评论

评论列表(0)

  1. 暂无评论