【问题标题】:Can't change State from child component even after passing a function from parent component即使从父组件传递函数后也无法从子组件更改状态
【发布时间】:2020-05-29 12:05:16
【问题描述】:

目前正在制作一个一开始有欢迎屏幕的待办应用,但是当点击按钮进入时,它会将欢迎状态从真设置为假。触发实际的待办事项列表组件。

由于某种原因,即使在将函数传递给 WelcomePage 之后,当我按下 enter 时,React 仍然不会渲染到其他组件。

谢谢,

function Router(props) {
    if (props.welcome) {
        return <WelcomePage onEnter={props.onEnter}/> //if home is true, there will be home page rendered
    } else { 
        return <ToDoPage/> //if home is false, that means you've entered
    }
}


class ToDo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {welcome: true};
        this.onEnter = this.onEnter.bind(this);
    }

    onEnter(e) {
        this.setState({welcome: false});
    }

    render() {
        return (
                <div className="ToDo">
                    <Router welcome={this.state.welcome} onEnter={this.onEnter}/>
                </div>
            )
    }
}
class WelcomePage extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div id="home">
                <h1> Welcome</h1>
                <h2> Who does this list beong to? </h2>
                <input placeholder="your name"/>
                <input type="button" value="enter" onSubmit={this.props.onEnter}/>
            </div>
            )
    }
}

【问题讨论】:

  • 无法识别是什么意思?是否有特定的错误,比如不能调用 null 的方法之类的?
  • 我不确定,我认为它没有注册该功能。当我按下回车键时,我无法让它更改组件。
  • 您能解释一下为什么您要尝试向按钮添加提交事件处理程序吗?你说的是onClick吗?还是您的意思是制作一个表单并处理表单的提交?
  • @AlexanderStaroselsky 哦,你解决了,我在那里犯了一个错误。

标签: javascript html reactjs components state


【解决方案1】:

尝试将onSubmit 更改为onClick,因为input:button 不会发出submit 事件:

class WelcomePage extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div id="home">
                <h1> Welcome</h1>
                <h2> Who does this list beong to? </h2>
                <input placeholder="your name"/>
                <input type="button" value="enter" onClick={this.props.onEnter}/>
            </div>
            )
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-18
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-15
    • 2019-11-16
    • 1970-01-01
    相关资源
    最近更新 更多