[英]Accessing return variable of React class component
I have react component which returns an integer. 我有反应成分,它返回一个整数。 Structure of the class component is as follows:
类组件的结构如下:
class MyClass extends Component {
constructor(props) {
super(props);
this.state = {
variable : 0
}
}
componentDidMount(){
// do some works
this.setSate({variable:$someValue});
}
render(){
var temp = this.state.variable;
return temp;
}
}
I need to fetch the value returned from MyClass in another class component in React within render. 我需要在渲染中的React的另一个类组件中获取MyClass返回的值。 If I call like,
如果我打来
render () {
return (
<div>{Myclass}</div>
);
}
it works fine. 它工作正常。 is there any way to call this outside return, and assign the value to a variable?
有什么方法可以调用此外部返回,并将值分配给变量?
Try utilizing 'this.props' instead. 尝试改用“ this.props”。 You can pass in something like this
你可以这样传递
class MyClass extends Component {
constructor(props) {
super(props);
this.state = {
variable : 0
}
}
componentDidMount(){
// do some works
this.setSate({variable:$someValue});
}
render(){
const {variable} = this.state
return (
<MyOtherClass variable = {variable}/>
);
}
}
And in MyOtherClass: 在MyOtherClass中:
render() {
const {variable} = this.props
return (
<div>{variable}</div>
);
}
You should be able to extend MyClass
and call super.render()
您应该能够扩展
MyClass
并调用super.render()
class MyOtherClass extends MyClass {
render() {
const value = super.render();
return (
<div>{value}</div>
);
}
}
edit : working example in codesandbox.io 编辑 : codeandbox.io中的工作示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.