简体   繁体   English

从另一个React脚本从导入的类访问变量

[英]Accessing variable from imported class from another React script

I'm importing a class from another script in my main React App, and would like to access a variable within that class from the main App. 我正在从我的主React App中的另一个脚本导入一个类,并且想从主App中访问该类中的变量。 Basically the user types something into a textbox, then clicks a button to add that value to a variable. 基本上,用户在文本框中键入内容,然后单击按钮以将该值添加到变量。 In the main App I import that class, then have another button to print those values (selectedvalues). 在主应用程序中,我导入该类,然后使用另一个按钮来打印这些值(selectedvalues)。 I'm not entirely sure how to do it, but this is my code so far: 我不完全确定该怎么做,但这是到目前为止的代码:

Class I am importing: 我正在导入的类:

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

And where I would like to actually access that value 而我想真正获得该价值的地方

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

Is there a way I can do this? 有办法吗?

Thanks! 谢谢!

Edit JS-fiddle here https://jsfiddle.net/xzehg1by/9/ 在这里编辑 JS小提琴https://jsfiddle.net/xzehg1by/9/

You can create Refs and access state and methods from it. 您可以创建引用并从中访问状态和方法。 Something like this. 这样的事情。

constructor() {
   this.myRef = React.createRef();
}

render() { ... <MyModule id='themodule' ref={this.myRef} /> }

printValues() {
   console.log(this.myRef)
}

more info here https://reactjs.org/docs/refs-and-the-dom.html 更多信息在这里https://reactjs.org/docs/refs-and-the-dom.html

Basically, your state ( selectedValues ) has to go one level up in the React tree. 基本上,您的状态( selectedValues )必须在React树中上移一层。 You have to declare it as App 's state, and then pass it down to MyModule via props. 您必须将其声明为App的状态,然后通过props将其传递给MyModule

Btw in addValue() , you're not changing any state. 顺便说一句,在addValue() ,您没有更改任何状态。 And this.selectedValues will be undefined. 并且this.selectedValues将是不确定的。 It's this.state.selectedValues , and this.props.selectedValues once you correct your code. 更正代码后,它就是this.state.selectedValuesthis.props.selectedValues

I think you should first read all react concepts and then start working on it. 我认为您应该先阅读所有反应概念,然后再着手进行研究。 Anyhow i am modifying your code in one way to get your desired functionality but remember this is not best practice you have to use Redux for this kind of features 无论如何,我正在以一种方式修改您的代码以获得所需的功能,但是请记住,这不是最佳实践,您必须将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

and your main component should be 而你的主要组成部分应该是

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

This should do your work 这应该做你的工作

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

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