簡體   English   中英

如何從父組件調用子組件功能?

[英]How to invoke child component function from parent component?

我有一個滿足以下條件的輸入字段組件:

最初關注時,在字段有效之前,什么也不會發生,然后應用有效的類

第一次模糊時,如果字段無效,則應用無效的類。

第一次模糊之后,一旦與該字段進行任何進一步的交互,只要該字段的值從有效變為無效,反之亦然,就會應用一個類。

為此,我做到了:

 import React, { Component } from "react"; class Input extends Component { constructor(props) { super(props); this.state = { touched: false, valid: false, focused: false, value: "" }; this.handleFocus = this.handleFocus.bind(this); this.handleBlur = this.handleBlur.bind(this); this.handleChange = this.handleChange.bind(this); } handleFocus() {} handleBlur() { if (!this.state.touched) { this.setState({ touched: true }); } else if (this.state.touched) { this.setState({ focused: true }); } } handleChange(e) { const val = e.target.value this.setState({ value: val }, () => { this.validateField(); } ); } validateField() { const touched = this.state.touched; const focused = this.state.focused; const valid = this.state.valid; const value = this.state.value; if (value.length >= 5) { this.setState({ valid: true, touched: true }); } else { this.setState({ valid: false }); } } render() { return ( <div> <input id={this.props.id} name={this.props.name} type="text" className={`form-control ${styles["kyi-input"]} ${ this.state.valid ? "is-valid" : "" } ${this.state.touched && !this.state.valid ? "is-invalid" : ""}`} required spellCheck="false" autoComplete="off" onFocus={this.handleFocus} onChange={this.handleChange} value={this.state.value} onBlur={this.handleBlur} placeholder={this.props.placeholder} /> </div> ); } } class Parent extends Component { handleInput(val, name) { // Can get value of input here this.setState({ [name]: val }); } render() { <Input placeholder="Test" onChange={(val) => {this.handleInput(val, 'inputName')}}/> } } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> 

它可以工作,但這意味着字段的狀態位於子組件而不是父組件中。

輸入字段的onBlur函數依賴於字段的狀態。

有沒有一種方法可以重構它,使輸入狀態位於父組件中,而onBlur函數位於子組件中?

我認為您應該在父組件中獲得所有狀態,還應該在父組件中獲得所有修改它的功能。 這將使您擁有一個“單一事實來源”,它可以跟蹤狀態的變化並將其傳遞給所有子組件。 查看提升狀態

暫無
暫無

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

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