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?
2 Answers
Reset to default 6As 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
版权声明:本文标题:javascript - React js: How to set props in JSX components which store in variable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744028876a2578543.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论