[英]React, accessing variable defined in componentDidMount from another function
[英]Accessing variable from imported class from another React script
我正在从我的主React App中的另一个脚本导入一个类,并且想从主App中访问该类中的变量。 基本上,用户在文本框中键入内容,然后单击按钮以将该值添加到变量。 在主应用程序中,我导入该类,然后使用另一个按钮来打印这些值(selectedvalues)。 我不完全确定该怎么做,但这是到目前为止的代码:
我正在导入的类:
import React, { Component } from 'react';
class MyModule extends Component {
constructor() {
super();
this.state = {
selectedValues: '',
}
}
addValue() {
this.selectedValues += document.getElementById('textBox1').value + ', '
return this.selectedValues
}
render() {
return(
<div>
<input type='text' id='textBox1' />
<button onClick={() => this.addValue()}>Add Value</button>
</div>
)
}
}
export default MyModule
而我想真正获得该价值的地方
import React, { Component } from 'react';
import MyModule from './myModule.js'
class App extends Component {
constructor() {
super();
this.state = {
}
}
printValues() {
console.log(document.getElementById('themodule').selectedvalues)
}
render() {
return(
<MyModule id='themodule' />
<button onClick={() => printValues()}>Print values</button>
)
}
}
export default App
有办法吗?
谢谢!
在这里编辑 JS小提琴https://jsfiddle.net/xzehg1by/9/
您可以创建引用并从中访问状态和方法。 这样的事情。
constructor() {
this.myRef = React.createRef();
}
render() { ... <MyModule id='themodule' ref={this.myRef} /> }
printValues() {
console.log(this.myRef)
}
基本上,您的状态( selectedValues
)必须在React树中上移一层。 您必须将其声明为App
的状态,然后通过props将其传递给MyModule
。
顺便说一句,在addValue()
,您没有更改任何状态。 并且this.selectedValues
将是不确定的。 更正代码后,它就是this.state.selectedValues
和this.props.selectedValues
。
我认为您应该先阅读所有反应概念,然后再着手进行研究。 无论如何,我正在以一种方式修改您的代码以获得所需的功能,但是请记住,这不是最佳实践,您必须将Redux用于此类功能
import React, { Component } from 'react';
class MyModule extends Component {
constructor() {
super(props);
this.state = {
inputValue : ''
};
this.handleInput = this.handleInput.bind(this);
this.addValue = this.addValue.bind(this)
}
handleInput(e){
this.setState({
inputValue : e.target.value
})
}
addValue() {
this.props.addValue(this.state.inputValue);
}
render() {
return(
<div>
<input type='text' id='textBox1' onChange={handleInput} />
<button onClick={this.addValue}>Add Value</button>
</div>
)
}
}
export default MyModule
而你的主要组成部分应该是
import React, { Component } from 'react';
import MyModule from './myModule.js'
class App extends Component {
constructor() {
super(props);
this.state = {
selectedValues : ''
};
this.printValues = this.printValues.bind(this);
this.addValues = this.addValues.bind(this);
}
printValues() {
console.log(this.state.selectedValues);
}
addValues(val){
this.setState({
selectedValues : this.state.selectedValues + " , "+val
})
}
render() {
return(
<React.Fragment>
<MyModule addValue={this.addValues}/>
<button onClick={this.printValues} >Print values</button>
</React.Fragment>
)
}
}
export default App
这应该做你的工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.