- 在父组件中定义一个事件函数,并将这个函数以属性的方式传递给子组件,在子组件中调用这个函数并将要传递的数据作为参数传递过去。
父组件:
import React from "react";
import CommentList from "./CommentList";
import CommentForm from "./CommentForm";
class CommentBox extends React.Component{
showSubmit(obj){
console.log(obj)
}
render(){
return(
<div>
<CommentList></CommentList>
{/* 将事件事件函数以属性方式传递给子组件,使子组件可以调用这个函数 */}
<CommentForm showSubmit={this.showSubmit}></CommentForm>
</div>
)
}
}
export default CommentBox;
子组件:
import React, { Component } from "react";
import { Form ,Input ,Button ,Radio } from "element-react";
import "element-theme-default";
class CommentForm extends Component{
//初始化状态
constructor(props) {
super(props);
this.state = {
form: {
name: '',
age:null,
sex:"",
}
};
}
//阻止表单提交默认事件
onSubmit(e) {
e.preventDefault();
}
//输入框内容变化时事件
onChange(key, value) {
this.state.form[key] = value;
this.forceUpdate();
}
//点击事件
onClick(){
let name = this.state.form.name;
let age = this.state.form.age;
let sex = this.state.form.sex;
//调用父组件中的事件函数,并将数据以参数的形式传递过去
this.props.showSubmit({name,age,sex})
}
render(){
return(
<Form model={this.state.form} labelWidth="80" onSubmit={this.onSubmit.bind(this)}>
<Form.Item label="姓名">
<Input value={this.state.form.name} onChange={this.onChange.bind(this, 'name')}></Input>
</Form.Item>
<Form.Item label="年龄">
<Input value={this.state.form.age} onChange={this.onChange.bind(this, 'age')}></Input>
</Form.Item>
<Form.Item label="性别">
<Radio.Group value={this.state.form.sex} onChange={this.onChange.bind(this, 'sex')}>
<Radio value="男"></Radio>
<Radio value="女"></Radio>
</Radio.Group>
</Form.Item>
<Form.Item>
<Button onClick={this.onClick.bind(this)}>确认</Button>
</Form.Item>
</Form>
)
}
}
export default CommentForm;
本文介绍在React应用中如何从子组件向父组件传递数据。通过父组件向子组件传递事件处理函数,子组件在特定操作后调用此函数,将所需数据作为参数传回。
743

被折叠的 条评论
为什么被折叠?



