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);
}
}
我想做的是,将#myinput
组件类中的变量(Request
值)传递给另一个组件类(validator
)中的函数(RequestValidator
)
到目前为止,我所做的是上面的代码,但是我得到了错误:
'validator'未定义为un-undef
答案 0 :(得分:2)
您可以使用ref
进行操作。您可以在父组件中创建一个:
class Request extends React.Component {
constructor(props) {
super(props)
this.requestValidatorRef = React.createRef();
}
然后将其传递给子组件:
<RequestValidator ref={this.requestValidatorRef} />
此时,您应该可以像这样调用您的方法:
getForm(e) {
this.requestValidatorRef.current.validator(e) // ...
}
答案 1 :(得分:0)
如果要将参数传递给reactjs中的另一个类,则应使用props。同样,requestvalidator类中的变量也必须使用道具名称。但是在您的情况下,RequestValidator和Input组件是不同的。 在这样的主要组件类调用中:
<UserInput
titles={this.state.titles}
/>
在UserInput组件中,像这样使用此道具:
class UserInput extends React.Component {
componentDidMount() {
console.log(" titles from main class:", this.props.titles);
}
}