传递给子组件的 React 单击处理程序不起作用

IT技术 reactjs
2021-05-07 06:10:13

我试图将点击处理程序传递给 SignIn 组件,但它对我不起作用。我得到日志然后页面刷新

Auth class:

class Auth extends Component {

login() {
    console.log('Clicked'); //only this method works
    fetch('/api/auth/signin', {
        method: 'POST',
        body: JSON.stringify(this.state),
        headers: {
            'Content-Type': 'application/json; charset=utf8'
        }
    }).then((response) => {
        if (response.status === 200) {
            this.props.history.push('/api/categories')
        }
    })
}

render() {
    return (
        <SignIn onCustomClick={this.login}/> //onClick handler
    )
}

登录组件

export default function SignIn(props) {
    const {onCustomClick} = props; // props
      return (
              <Button
                type="submit"
                fullWidth
                variant="contained"
                color="primary"
                className={classes.submit}
                onClick={onCustomClick} // onClick handler
              >)
    }
2个回答

您需要将登录功能绑定到类上下文把它写成一个arrow function来实现这一点。

还添加e.preventDefault以防止表单提交时的默认浏览器行为以使用提交的信息刷新页面

class Auth extends Component {

    login = (e) =>  { // Arrow function here
        e.preventDefault(); // prevent default browser behaviour to refresh
        fetch('/api/auth/signin', {
            method: 'POST',
            body: JSON.stringify(this.state),
            headers: {
                'Content-Type': 'application/json; charset=utf8'
            }
        }).then((response) => {
            if (response.status === 200) {
                this.props.history.push('/api/categories')
            }
        })
    }

    render() {
        return (
            <SignIn onCustomClick={this.login}/> //onClick handler
        )
    }

}

您的登录函数未绑定,您可以使用箭头函数或在构造函数中显式绑定它以使其工作。

class Auth extends Component {
constructor(props){
  super(props);
  // here your function is binded
  this.login = this.login.bind(this);
}

login() {
    console.log('Clicked'); //only this method works
    fetch('/api/auth/signin', {
        method: 'POST',
        body: JSON.stringify(this.state),
        headers: {
            'Content-Type': 'application/json; charset=utf8'
        }
    }).then((response) => {
        if (response.status === 200) {
            this.props.history.push('/api/categories')
        }
    })
}

render() {
    return (
        <SignIn onCustomClick={this.login}/> //onClick handler
    )
}