admin管理员组

文章数量:1355542

Suppose I already define an ponent:

class Co extends React.Component {
    render = () => {
        const name = this.props.name;
        return (
            <p>Hello, my name is {name}</p>
        )
    }
}

and store it in an variable:

const co = <Co />;

How can I set the ponent's props with the variable? Would co.props.set work?

Suppose I already define an ponent:

class Co extends React.Component {
    render = () => {
        const name = this.props.name;
        return (
            <p>Hello, my name is {name}</p>
        )
    }
}

and store it in an variable:

const co = <Co />;

How can I set the ponent's props with the variable? Would co.props.set work?

Share Improve this question asked Jul 1, 2016 at 12:20 hh54188hh54188 15.7k35 gold badges116 silver badges192 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

As I understand you don't want to render your ponent in JSX syntax but with your stored variable. You can have a look at React.cloneElement. This should do what you want:

{React.cloneElement(co, {name: 'hans'})}

See: https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement

You can set props as usual

<Co name="Name"/>

If element is child of some ponent then you can use React.cloneElement()

class Parent extends React.Component {
    render = () => {
        const name = this.props.name;
        return (
            <SomeComp><Co/></SomeComp>
        )
    }
}
class SomeComp extends React.Component {
    render = () => {
        const name = this.props.name;
        return (
            <SomeComp>{React.cloneElement(this.props.children, {name:"Name"})}</SomeComp>
        )
    }
}

本文标签: javascriptReact js How to set props in JSX components which store in variableStack Overflow