React,onChange和onClick事件同时触发

时间:2018-04-09 11:10:01

标签: reactjs onclick onchange

我的应用程序出了问题:当用户输入(并且我猜想onChange被触发)时,即使是一个字母,下面的onClick事件也会被触发。我的错误在哪里? 我已经简化了代码(在那里你看到了评论),那里没有相关的代码! 谢谢大家!

class Project extends React.Component {
    constructor() {
        super();
        this.state = {
            section_title: '',
            sections: []
        }

        this.handleChange = this.handleChange.bind(this);
        this.createSection = this.createSection.bind(this);
        this.getSections = this.getSections.bind(this);
    }

    handleChange(event) {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;

        this.setState({
            [name]: value
        });
    }

    createSection(project_id) {
        if(this.state.section_title != '') {
            //Do Something here
        }
    }

    getSections(project_id) {
        //Fetch data here
    }

    componentDidMount() {
        let project_data = this.props.project[0];

        this.getSections(project_data.uid);
    }

    render() {
        let project_data = this.props.project[0];

        return (
            <div>
                <h2 className="ui header">
                    <i className="folder outline icon"></i>
                    <div className="content">
                        {project_data.title}
                        <div className="sub header">{he.decode(project_data.description)}</div>
                    </div>
                </h2>
                <div className="ui divider"></div>

                <Modal trigger={<Button color="teal">Add New Section</Button>} closeIcon>
                    <Modal.Header>Add new section</Modal.Header>
                    <Modal.Content image>
                        <Modal.Description>
                        <Form>
                            <Form.Field>
                                <label>Section Name</label>
                                <input name="section_title" placeholder='Es: Slider ecc...' value={this.state.section_title} onChange={this.handleChange} />
                            </Form.Field>
                            <Button color="green" type='submit' onClick={this.createSection(project_data.uid)}>Crea Sezione</Button>
                        </Form>
                        </Modal.Description>
                    </Modal.Content>
                </Modal>
            </div>
        );
    }
}

2 个答案:

答案 0 :(得分:0)

您所做的基本上是使用createSection的{​​{1}}函数的返回数据

因此,在onClick上,请尝试

onClick

onClick={() => this.createSection(project_data.uid)} 部分已经正确。

此问题类似于现有的已回答问题:React onClick function fires on render

答案 1 :(得分:0)

在按钮中

,您正在初始化函数this.createSection(project_data.uid),而不是在需要时调用它。最简单的方法是通过箭头功能调用  onClick={() => this.createSection(project_data.uid)}