【问题标题】:Forms with React components带有 React 组件的表单
【发布时间】:2017-05-22 20:50:00
【问题描述】:

我想用 React 创建一个表单。我想出了以下几点:

export class Welcome extends Component {

    constructor(props) {
        super(props);
        this.state = {
            errors: []
        };
    }

    render() {
        return (
            <form className="Welcome">
                <div className="hello">{ this.props.sayHello() } I'm <Link to="/life">Marco</Link>! Welcome to my hood.</div>
                <div className="question-box">
                    <div className="question"><span className="underline" >How much time do you have?</span></div>
                    <input className="minutes" type="text" value={this.props.minutes}
                           onChange={ (e) => this.props.updatePreferences("minutes", e.target.value) }/> minutes. 
                </div>
                <div className="question-box">
                    <div className="question"><span className="underline">What do you fancy?</span></div>
                    <div className="answer">
                        <span className="choice">
                            <input type="checkbox" id="business" defaultChecked={ this.props.interests.business }/>
                            <label htmlFor="business">Business</label>
                        </span>
                        <span className="choice">
                            <input type="checkbox" id="code" defaultChecked={ this.props.interests.code }/>
                            <label htmlFor="code">Code</label>
                        </span>
                        <span className="choice">
                            <input type="checkbox" id="design" defaultChecked={ this.props.interests.design } />
                            <label htmlFor="design">Design</label>
                        </span>
                    </div>{/* end of .answer*/}
                  </div>{/* end .question-box*/}
                <button>Show me magic</button>
                <div className="errors">
                    No error. All good.
                </div>
            </form>
        );
    }
}

onChange 函数在也持有状态的父组件中。但是每次调用它们时,都会重新加载整个组件。整个表单应该在一个单独的组件上还是我应该为每个输入创建单独的组件?

【问题讨论】:

  • 让你的组件尽可能简单。是的,你应该尽量保持你的组件小。
  • 将重复的代码转换成组件。

标签: reactjs jsx


【解决方案1】:

React 调用渲染函数以响应状态变化。因此,如果组件没有收到状态更改事件,它很可能不会重新渲染,但不一定。无论如何它可能会重新出现。 ref

【讨论】:

    猜你喜欢
    • 2019-07-02
    • 2020-12-02
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2016-08-18
    相关资源
    最近更新 更多