簡體   English   中英

從子 class 訪問父 class 中的 state

[英]Accessing state in parent class from a child class

我感謝此列表中先前的幫助。 這就是我想要做的。 使用 get 或 post 與服務器通信並在 JSON 中接收響應的一組級聯類。 我過去曾使用 HTML5、javascript 和 JQuery 成功完成此操作。 我想要使用 React 的新代碼。 我已經閱讀了許多記錄組件、道具和類的文章。 我還不太明白。 我相信我的嘗試很接近,但仍然是錯誤的。 Babel 給了我一個語法錯誤。 查看失敗的代碼:

class NameForm extends React.Component {
                      constructor(props) {
                        super(props);
                        this.state = {
                          value: ''
                        };
                        this.handleChange = this.handleChange.bind(this);
                        this.handleSubmit = this.handleSubmit.bind(this);
                      }

                      handleChange(event) {
                        const regexpr = /^[0-9\b]+$/;
                        if(event.target.value === '' || regexpr.test(event.target.value)){
                            this.setState({
                            value: event.target.value
                            });
                        }
                      }

                      handleSubmit(event) {
                        alert('A name was submitted: ' + this.state.value);
                        const {theName} = this.state.value;
                        return <NameProcess {"theName"}/>;  /* FAIL ! */
                      }

                      render() {
                        return /*#__PURE__*/React.createElement("form", {
                          onSubmit: this.handleSubmit
                        }, /*#__PURE__*/React.createElement("label", null, "Name:", 
/*#__PURE__*/React.createElement("input", {
                          type: "text",
                          value: this.state.value,
                          onChange: this.handleChange
                        })), /*#__PURE__*/React.createElement("input", {
                          type: "submit",
                          value: "Submit"
                        }));
                  }
                }

NameProcess 將是子 class 的名稱。 作為初學者,我做錯了什么?

您必須將值傳遞給子組件NameProcess將查找的特定道具。 例如, return <NameProcess value={theName} />; 然后通過this.props.value在子組件中訪問它。 但是, const {theName} = this.state.value將返回undefined ,除非value是具有屬性theName的 object 。 您可能想改用const { value } = this.state

而且,我不確定你為什么要從handleSubmit function 返回這個組件。 如果您嘗試等待提交直到顯示組件,您可以做的是將其添加到您的 state 以標記何時提交表單:

this.state = { value: '', submitted: false };

並向您的handleSubmit以將值更新為true

handleSubmit(event) {
    event.preventDefault(); // to prevent default action taken on form submit
    alert('A name was submitted: ' + this.state.value);
    this.setState({ submitted: true });
}

並在您的渲染 function 提交后顯示子組件:

{this.state.submitted && return <NameProcess value={this.state.theName} />}

正如@Yossi 提到的,您可能希望使用 JSX 清理您的render function,制作整個文件,將所有這些建議放在一起,如下所示:

class NameForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: '',
            submitted: false
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        const regexpr = /^[0-9\b]+$/;
        if(event.target.value === '' || regexpr.test(event.target.value)){
            this.setState({
                value: event.target.value
            });
        }
    }

    handleSubmit(event) {
        event.preventDefault();
        const { value } = this.state;
        alert('A name was submitted: ' + value);
        this.setState({ submitted: true });
    }

    render() {
        const { value, submitted } = this.state;
        return (
            {submitted ? <NameProcess value={value} /> : (
                <form onSubmit={this.handleSubmit}>
                    <label>Name:</label>
                    <input type="text" value={value} onChange={this.handleChange} />
                    <input type="submit" value="Submit" />
                </form>
            )}
        );
    }
}

這行得通。

class NameForm extends React.Component {  /*1*/
                      constructor(props) { /*2*/
                        super(props);
                        this.state = { /*3*/
                          value: '',
                          submitted: false
                        }; /*3*/
                        this.handleChange = this.handleChange.bind(this);
                        this.handleSubmit = this.handleSubmit.bind(this);
                      } /*2*/

                      handleChange(event) { /*2 */
                        const regexpr = /^[0-9\b]+$/;

                        if (event.target.value === '' || 
regexpr.test(event.target.value)) { /* 3 */
                          this.setState({ /* 4 */
                            value: event.target.value
                          }); /* 4 */
                        } /* 3 */
                      } /* 2 */

                      handleSubmit(event) { /* 2 */
                        event.preventDefault();
                        const { /* 3 */
                          value
                        } = this.state; /* 3 */
                        alert('A name was submitted: ' + value);
                        this.setState({ /* 3 */
                          submitted: true
                        }); /* 3 */
                      } /* 2 */

                      render() { /* 2 */
                                return this.state.submitted ? 
/*#__PURE__*/React.createElement(NameProcess, { /* 3 */
                                  value: this.state.value
                                }) : 
                                     /*#__PURE__*/React.createElement("form", { /* 3 */ /* 3 */ 
                                       onSubmit: this.handleSubmit
                                }, 
                                /*#__PURE__*/React.createElement("label", null, "Name:"), /*#__PURE__*/React.createElement("input", { /* 3 */ /* 3 */ 
                                  type: "text",
                                  value: this.state.value,
                                  onChange: this.handleChange
                                }), 
                                /*#__PURE__*/React.createElement("input", { /* 3 */ /* 3 */ 
                                  type: "submit",
                                  value: "Submit"
                                })); /* 3 */ 

                              } /* 2 */
                      } /* 1 */

                      class NameProcess extends React.Component {  /*1*/
                          constructor(props) { /*2*/
                            super(props);
                          } /*2*/
                          render(){ /* 2 */
                                  return 'blah!';
                              }  /* 2 */
                      } /* 1 */

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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