简体   繁体   中英

Dynamic attributes on a react component element

I am trying to build a dynamic as possible app. So I thought why not build elements from just passing a json object to it.

I have this:

[
    {
        key: 1,
        element: 'input',
        type: 'text',
        placeholder: 'Jamie is'
    },
    {
        key: 2,
        element: 'input',
        type: 'text',
        placeholder: 'Jamie is Not'
    },
    {
        key: 3,
        element: 'input',
        type: 'password',
        placeholder: 'Jamie is'
    }
]

Each element from the array will get passed to my elements, so instead of having to define each attribute I'd like to just make sure I pass the correct attributes and have it build on the flu.

All hell breaks loose when I do this:

const input = React.createClass ({
    render() {
        let data = this.props.data;
        return (
            <input placeholder={data.placeholder} /> //current
            <input {data} /> //desired
        );
    }
});

I'm not sure that is the best idea, but being that I'm not aware of your full requirements, here we go. To make this work, you could try doing {...data} instead of {data} in the <input/> element. However, custom attributes have certain reservations. Please refer to this section of the React documentation for more information. Also here is some more information about what the three dots (...) are for.

The custom input component with the data prop seems weird and messy to me.

It's pretty easy to build elements dynamically if you just look at what Babel compiles <input foo={bar} /> to. Given your array of data all you have to do is

var inputs = data.map(
  ({element, ...props}) => React.createElement(element, props)
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM