How to create a dynamic prop name in React?

后端 未结 3 693
谎友^
谎友^ 2021-01-31 15:34

Is it possible to create the name of a prop dynamically? For example:

let dynamicPropName = \"someString\";

         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-31 15:54

    If you are using es6, you can define the dynamic prop:

    let dynamicProps = {"dynamicKey":"someString", "dynamicKey2":"someString"};
    

    or

    let someVariable = "xyz";
    dynamicProps[someVariable] = value;
    

    then use the spread operator:

    
    

    Inside MyComponent -

    let props = {...this.props};
    

    Now you can use Object.keys on props to get all dynamic prop names.

    Edit: Added an example

    class Test extends React.Component {
      
      renderFromProps() {
        return Object.keys(this.props)
        .map((propKey) =>
          

    {this.props[propKey]}

    ); } render() { return (

    One way


    {this.props.name}

    {this.props.type}

    {this.props.value}


    Another way


    { this.renderFromProps()}
    ); } } const dynamicProps = { name:"Test", type:"String", value:"Hi" }; ReactDOM.render( , document.getElementById('root') );
    
    
    

提交回复
热议问题