目标:
子组件中发送请求后获取数据传递给父组件展示
实现思想:
子组件通过props控制父组件的方法触发,将子组件中的值通过此方法传给父组件。
案例:
父组件Authentication:
import React from "react";
import "./style.scss";
import AuthenticationItem from './AuthenticationItem';
interface IAuthenticationState{
realName: string;
idCode: string;
}
class Authentication extends React.Component<{},IAuthenticationState> {
constructor(props: any) {
super(props);
this.state={
realName: '',
idCode: ''
}
}
handleName(name:any,id:any){
this.setState ({
realName: name,
idCode: id
})
}
public render() {
const { isAuthentication, realName, idCode } = this.state;
return (
<div className="w w1 authentication clearfix">
<AuthenticationItem className="sfz-front" title="身份证背面" key="0"
handleName={this.handleName}/>
<div className="auth-item owner">
<span className="lb">机主姓名:</span>
<input className="auth-name auth-plugin-name" name="certName" placeholder="请填写机主姓名"
value={realName}
onChange={this.handleRealNameChange}/>
<span className="auth-error">请填写机主姓名</span>
</div>
<div className="auth-item idNumber">
<span className="lb">身份证号:</span>
<input className="auth-name auth-plugin-name" name="certName" placeholder="请填写证件号码"
value={idCode}
disabled={idCode ? true : false}/>
<span className="auth-error">请填写身份证号</span>
</div>
</div>
</div>
</div>
}
</div>
)
}
}
export default Authentication;
子组件AuthenticationItem :
import React from "react";
import "./AuthenticationItemStyle.scss";
import { func } from 'prop-types';
interface IAuthenticationItemProps{
handleName: (name:any,idCode:any)=>void;
}
interface IAuthenticationItemState{
}
class AuthenticationItem extends React.Component<IAuthenticationItemProps,IAuthenticationItemState> {
static defaultProps = {
handleName: func
}
constructor(props: any) {
super(props);
this.state={
}
}
handleImageChange(e){
const url = "...";
const options = {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST",
body: JSON.stringify({
htId: "",
imageType: "",
img: dataURl
})
};
return fetch(url, options).then(res => res.json(), err=>{
console.log(err)
}).then((data) => {
console.log(data)
if (data.code === 200) {
this.props.handleName(data.data.realName,data.data.idCode);
}
},err1 => {
console.log(err1)
});
};
}
export default AuthenticationItem;
注意其中的handleName方法!!!