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

时间:2020-05-14 06:45:25

标签: reactjs

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

Auth类:

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 个答案:

答案 0 :(得分:1)

您需要将登录功能绑定到类上下文。将其写为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
        )
    }

}

答案 1 :(得分:0)

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

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
    )
}