Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在条件组件内处理onClick事件_Javascript_Reactjs_Next.js_Bootstrap Typeahead - Fatal编程技术网

Javascript 如何在条件组件内处理onClick事件

Javascript 如何在条件组件内处理onClick事件,javascript,reactjs,next.js,bootstrap-typeahead,Javascript,Reactjs,Next.js,Bootstrap Typeahead,我正在尝试对从AsyncTypeahead中选择的数据添加onClick事件。我将回调函数传递给仅当我选择了一个项时才呈现的问题。但在选择一个项之后,它会直接调用我传递给问题组件的回调函数 这是主要组成部分 constructor(props) { super(props); this.state = { plateform: '', selected: [], isLoading: false, options:

我正在尝试对从AsyncTypeahead中选择的数据添加onClick事件。我将回调函数传递给仅当我选择了一个项时才呈现的问题。但在选择一个项之后,它会直接调用我传递给问题组件的回调函数

这是主要组成部分

constructor(props) {
    super(props);

    this.state = {
        plateform: '',
        selected: [],
        isLoading: false,
        options: []
    };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.saveTodo = this.saveTodo.bind(this);
}

async handleInputChange(event) {
    const target = event.target;
    const value = target.value;
    const name = target.name;

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

saveTodo(problemID) {
    axios.post(`${API}/todos`,
    {
        problemID: problemID
    },
    {
        headers: {
            Accept: "application/json",
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + this.props.auth.token
        }
    })
    .then(() => alert("Problem saved to todo list"))
    .catch((err) => {
        if (err.response) {
            alert(err.response.data);
        }
        else {
            alert("Sorry! A server error occurred. Try to save this problem later!");
        }
    });
}


render() {

    return (
        <>
            <TrainLayout auth={this.props.auth} deauthenticate={this.props.deauthenticate} title={title} description={description} >
                <div className="container">
                    <div className="row justify-content-center">
                        <div className="offset-md-3 col-md-7 offset-2">
                            <br />
                            <div className="form-group row">
                                <label htmlFor="oj" className="col-4 col-form-label col-form-label-sm">Online Judge</label>
                                <div className="col-8 col-md-5">
                                    <select id="oj" type="select" className="form-control form-control-sm" name="plateform" onChange={this.handleInputChange} value={this.state.plateform}>
                                        <option value="all">All Online Judges</option>
                                        <option value="xxx">XXX</option>
                                        <option value="yyy">YYY</option>
                                        <option value="zzz">ZZZ</option>
                                    </select>
                                </div>
                            </div>
                            <div className="form-group row">
                                <label htmlFor="pname" className="col-4 col-form-label col-form-label-sm">Problem Name</label>
                                <div className="col-8 col-md-5">
                                    <AsyncTypeahead
                                        isLoading={this.state.isLoading}
                                        allowNew={false}
                                        multiple={false}
                                        id="pname"
                                        labelKey={option => `${option.name} (${option.plateform})`}
                                        minLength={2}
                                        onChange={selected => this.setState({ selected })}
                                        placeholder="Search for a problem"
                                        onSearch={query => {
                                            this.setState({isLoading: true});
                                            axios.get(`${API}/problems/${query}`,
                                            {
                                                params: {
                                                    plateform: this.state.plateform
                                                },
                                                headers: {
                                                    Accept: "application/json",
                                                    'Content-Type': 'application/json',
                                                    'Authorization': 'Bearer ' + this.props.auth.token
                                                }
                                            })
                                            .then((response) => { /* eslint-disable-line camelcase */
                                                const options = response.data.map((problem) => ({
                                                    _id: problem._id,
                                                    problemID: problem.problemID,
                                                    name: problem.name,
                                                    plateform: problem.plateform,
                                                    link: problem.link,
                                                    difficulty: problem.difficulty
                                                }));
                                                console.log("DATA: ", options);
                                                this.setState({
                                                    isLoading: false,
                                                    options: options,
                                                });
                                            });
                                        }}
                                        options={this.state.options} />
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
                <br /><br />
                <div className="container">
                    <div className="row justify-content-center">
                        {!!this.state.selected &&
                        (
                        <Problem saveTodo={this.saveTodo} problem={this.state.selected[0]} />)
                        }
                    </div>
                </div>
            </TrainLayout>
        </>
    );
}
构造函数(道具){
超级(道具);
此.state={
平台:“”,
选定:[],
孤岛加载:false,
选项:[]
};
this.handleInputChange=this.handleInputChange.bind(this);
this.saveTodo=this.saveTodo.bind(this);
}
异步handleInputChange(事件){
const target=event.target;
常量值=target.value;
const name=target.name;
等待这一天({
[名称]:值
});
}
saveTodo(问题ID){
post(`${API}/todos`,
{
problemID:problemID
},
{
标题:{
接受:“应用程序/json”,
“内容类型”:“应用程序/json”,
“授权”:“持有人”+this.props.auth.token
}
})
。然后(()=>警报(“问题已保存到待办事项列表”))
.catch((错误)=>{
如果(错误响应){
警报(错误响应数据);
}
否则{
警报(“抱歉!发生服务器错误。请稍后尝试保存此问题!”);
}
});
}
render(){
返回(

在线法官 所有在线评委 XXX YYY ZZZ 问题名称
注:难度并非100%准确

);}
您应该将函数作为事件处理程序传递。在您的示例中,您正在立即调用该函数。尝试以下方法

<td> <a onClick={() => saveTodo(problem.problemID)}><FontAwesomeIcon icon="save" /></a> </td>
了解更多信息

<td> <a onClick={() => saveTodo(problem.problemID)}><FontAwesomeIcon icon="save" /></a> </td>