[英]How to pass handler in react-redux
我正在研究一个用react-redux编写的项目。 我想将处理程序传递给子组件,以便可以从子组件触发处理程序。
我的父组件代码
import React from 'react';
import Input from 'src/containers/Input';
export default class AddChannelComponent extends React.Component<void, PropsType, void> {
render() {
function inputHandler (value){
console.log("value is",value);
}
return (
<div >
<p>Type your input</p>
<div>
<Input inputHandler={this.inputHandler} placeholder="Search all public channels..." />
</div>
</div>
);
}
}
Input是一个js文件,该文件调用组件InputComponent.js
Input.js文件的代码为:
import { connect } from 'react-redux';
import InputComponent from 'src/components/InputComponent';
const mapStateToProps = (state) => ({
});
const mapDispatchToProps = (dispatch) => ({
});
const Input = connect(
mapStateToProps,
mapDispatchToProps
)(InputComponent);
export default Input;
现在,我的InputComponent.js文件代码为:
import React from 'react';
export default class InputComponent extends React.Component<void, PropsType, void> {
callHandler = event => {
console.log("value in input",event.target.value);
this.props.inputHandler(event.target.value) <== Error Occur
}
render() {
return (
<input {...this.props} onChange={this.callHandler}/>
);
}
}
this.props.inputHandler(event.target.value)给我这样的错误:_this.props.inputHandler不是函数。 如何在子组件中调用父处理程序。
提前致谢。
inputHandler = (value) => {
console.log("value is",value);
}
render() {
......
代替
render() {
function inputHandler (value){
console.log("value is",value);
}
......
在AddChannelComponent
类的范围内编写inputHandler
函数,然后使用this.inputHandler
如果您使用的是闭包函数(在您的情况下),请直接使用inputHandler
作为
<Input inputHandler={inputHandler} placeholder="Search all public channels..." />
只是一个简短的答案:您是否尝试过将inputHandler
fn定义为类方法? 您尝试通过this.inputHandler
访问它,但fn是在render方法中定义的。
根据React Docs ,您应该绑定方法:
您必须小心JSX回调中的含义。 在JavaScript中,默认情况下不绑定类方法。 如果忘记绑定this.handleClick并将其传递给onClick,则在实际调用该函数时将无法定义。
这不是特定于React的行为; 它是函数在JavaScript中工作方式的一部分。 通常,如果您引用的方法后面没有(),例如onClick = {this.handleClick},则应绑定该方法。
如果使绑定烦恼,可以通过两种方法解决此问题。 如果使用实验性属性初始化程序语法,则可以使用属性初始化程序正确绑定回调
因此,在您的示例中:
import React from 'react';
export default class InputComponent extends React.Component<void, PropsType, void> {
callHandler = event => {
console.log("value in input",event.target.value);
this.props.inputHandler(event.target.value) <== Error Occur
}
render() {
return (
<input {...this.props} onChange={this.callHandler.bind(this)}/>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.