簡體   English   中英

React 將狀態從子級傳遞到父級

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM