简体   繁体   English

React js:如何在JSX组件中设置存储在变量中的props

[英]React js: How to set props in JSX components which store in variable

Suppose I already define an component: 假设我已经定义了一个组件:

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 component's props with the variable? 如何使用变量设置组件的道具? Would co.props.set work? co.props.set工作吗?

As I understand you don't want to render your component in JSX syntax but with your stored variable. 据我所知,您不希望使用JSX语法渲染组件,而是使用存储的变量。 You can have a look at React.cloneElement . 你可以看一下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 请参阅: 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 component then you can use React.cloneElement() 如果element是某个组件的子元素,那么你可以使用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>
        )
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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