[英]React Passing state from child to parent
我有一个文件上传小部件,一旦文件成功上传,它应该更改父级中的状态,然后将组件切换到“处理”。
但是我当前状态的代码给出了错误:
期望赋值或函数调用,却看到了一个表达式 no-unused-expressions
如何在成功上传后从 fileUploadWidget 更新父级 (UploadRequired) 的状态?
家长:
class UploadRequired extends Component {
constructor(props) {
super(props);
this.state = {status: ""};
this.handler = this.handler.bind(this);
}
handler() {
this.setState({
state: "0"
});
}
componentWillReceiveProps = props => {
this.setState({ status : props.dataRow });
}
render() {
var button = <div></div>;
if(this.state.status == ""){
button = <FileUploadWidget file={this.props.file} payrollID={this.props.payrollID} action={this.handler}/>;
}
if(this.state.status == "0"){
button = <ProcessWidget />;
}
if(this.state.status == "1"){
button = <ProcessingWidget />;
}
if(this.state.status == "2"){
button = <ProcessedWidget />;
}
return(
<div>
{button}
</div>
)
}
}
export default UploadRequired;
孩子:
class FileUploadWidget extends Component {
constructor(props, context) {
super(props, context);
}
componentDidMount() {
var self=this;
let fileName = this.props.file
let payrollID = this.props.payrollID
const inputElement = document.getElementById(this.props.file);
if(inputElement){
inputElement.addEventListener("change", handleFiles, true);
}
function handleFiles() {
var self=this;
const fileList = this.files;
const uri = "http://*******/fileupload.php";
const xhr = new XMLHttpRequest();
const fd = new FormData();
xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Error line here
this.props.action
}
if (xhr.readyState == 4 && xhr.status == 400) {
alert(xhr.responseText);
}
};
xhr.send(fd);
}
}
render() {
return (
<div>
<input type="file" id={this.props.file}></input>
</div>
)
}
}
const self = this;
const promise1 = new Promise(function(resolve, reject) {
resolve(()=>{
return self.props.action()
})
});
await promise1()
console.log(promise1);
好吧, this.props.action
只是处理函数,你不需要this.props.action()
吗?
您还需要绑定handler
,使this
作品的时候,它被称为: this.handler.bind(this)
,或通过拉姆达到子action={() => this.handler()}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.