简体   繁体   中英

Reactjs pass variable to function from another class

Request.js

export default class Request extends React.Component {
getForm(e) {
  let v = validator(document.getElementById('myinput')); // here is should call function from another class
}
render(){
  return(
      <form onSubmit={this.getForm.bind(this)}>
        <RequestValidator/> // here is I called second class
        <Input id="myinput" value="65"/>
      </form>
    }
  }
}

RequestValidator.js

export default class RequestValidator extends React.Component {
  validator = (e) => { // here is the target function
    console.log(e.value);
  }
}

What I want to do is, pass a variable ( #myinput value) from Request compontent class to a function ( validator ) in another compontent class ( RequestValidator ).

What I have done so far is above codes, but I got error:

'validator' is not defined no-undef

You can do that using ref . You create one in your parent component:

class Request extends React.Component {
    constructor(props) {
        super(props)
        this.requestValidatorRef = React.createRef();
    }

then you pass it to the child component:

<RequestValidator ref={this.requestValidatorRef} />

at this point you should be able to call your method like this:

getForm(e) {
  this.requestValidatorRef.current.validator(e) // ...
}

If you want to pass parameter to another class in reactjs you should use props. Also variable in requestvalidator class have to use prop name. But in your case RequestValidator and Input components are different. In main component class call like this:

  <UserInput
         titles={this.state.titles}
    />

In UserInput component use this prop like this:

class UserInput extends React.Component {
      componentDidMount() {
        console.log(" titles from main class:", this.props.titles);
      }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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