访问子组件中父组件的状态?

IT技术 javascript reactjs ecmascript-6 state react-props
2021-05-14 09:34:23

我是 React js 的新手,我需要让另一个类访问组件的状态,我遇到了这个问题,因为我使用的是原子设计,因为在一个组件中编写所有内容都变成了一个问题,这里是我的代码: Headcomponent

class Headcomponent extends React.Component{

  constructor (props) {

    super(props);
    this.state = {
      email: '',
      password: '',
      formErrors: {email: '', password: ''},
      emailValid: false,
      passwordValid: false,
      formValid: false,
      items: [],

    }
  }


    this.setState({formErrors: fieldValidationErrors,
                    emailValid: emailValid,
                    passwordValid: passwordValid
                  }, this.validateForm);
}

validateForm() {
  this.setState({formValid: this.state.emailValid && 
  this.state.passwordValid});
}


render(){
        return (
  <Form fields={this.props.form} buttonText="Submit" />
        );
    }
}


Headcomponent.propTypes = {
  form: PropTypes.array,
};

Headcomponent.defaultProps = {
  form: [
    {
      label: 'label1',
      placeholder: 'Input 1',
    },
    {
      label: 'label2',
      placeholder: 'Placeholder for Input 2',
    },
  ],
};

export default Headcomponent;

表单.js

   const Form = props => (
      <form className="Form">
        {
          props.fields.map((field, i) => (<LabeledInput label={field.label} placeholder={field.placeholder} key={i}/>))
        }
        <Button text={props.buttonText} />
      </form>
    );

    Form.propTypes = {
      fields: PropTypes.arrayOf(PropTypes.object).isRequired,
      buttonText: PropTypes.string.isRequired,
    };

    export default Form;

LabeledInput.js(我需要在这里传递我的密码状态)

const LabeledInput = props => (
  <div className={`form-group `} >
    <Label text={props.label} />
    <Input value={props.value} placeholder={props.placeholder} type="text" onChange={props.onChange} />
    <div class="valid-feedback">{props.errorMessage}</div>
    <small class="form-text text-muted">{props.exampleText}</small>
  </div>
);

LabeledInput.propTypes = {
  label: PropTypes.string.isRequired,
  placeholder: PropTypes.string,
  onChange: PropTypes.func.required,
  value: PropTypes.string.isRequired,
  exampleText: PropTypes.string,
  errorMessage: PropTypes.string,
};

export default LabeledInput;

如何访问 headComponent 中的状态LabeledInput

4个回答

最合理的方法是将它(您需要的状态的值Headcomponent)作为props传递

头组件.js

class Headcomponent extends React.Component {
  constructor (props) {
    super(props);

    this.state = {
      email: '',
      password: '',
      formErrors: {email: '', password: ''},
      emailValid: false,
      passwordValid: false,
      formValid: false,
      items: [],
    }
  }

  render() {
    return (
      <Form
        fields={this.props.form}
        formValid={this.state.formValid}  // from Headcomponent's state
        buttonText="Submit"
      />
    );
  }
}

表单.js

const Form = props => (
   <form className="Form">
     {
       props.fields.map((field, i) => (
         <LabeledInput
           label={field.label}
           formValid={props.formValid}  // from Headcomponent's state
           placeholder={field.placeholder}
           key={i}
         />
       ))
     }
     <Button text={props.buttonText} />
   </form>
 );

标记输入.js

 const LabeledInput = props => (
   <div className={`form-group `} >
     { props.formValid && 'This form is valid' }  // from Headcomponent's state
     <Label text={props.label} />
     <Input value={props.value} placeholder={props.placeholder} type="text" onChange={props.onChange} />
     <div class="valid-feedback">{props.errorMessage}</div>
     <small class="form-text text-muted">{props.exampleText}</small>
   </div>
 );

因此,如果任何时候Headcomponent的状态更新,它将被传播到LabeledInput组件

访问headComponentin LabeledInputin状态以继续传递它的最简单方法

如果你想this.state.passwordheadComponent内部访问值LabeledInput那么你可以将它this.state.password作为 prop传递给 render 方法中的表单组件

   render(){
        return (
          <Form 
            fields={this.props.form} 
            buttonText="Submit" 
            password={this.state.password} />
        );
    }

然后,这使您可以访问this.state.password作为 Form 组件内的props。然后重复该过程并将其传递给LabeledInput表单内组件

const Form = props => (
      <form className="Form">
        {
          props.fields.map((field, i) => (
            <LabeledInput 
                label={field.label} 
                placeholder={field.placeholder} 
                key={i}
                password={this.props.password}
             />))
        }
        <Button text={props.buttonText} />
      </form>
    );

然后,您可以LabeledInput通过调用访问组件内的值this.props.password

您可以使用它props来实现这一点。

根组件:

<div>
  <child myState="hello"></child>
</div>

子组件:

<div>
  <child2 myOtherProperty={this.props.myState}></child2>
</div>

Child1 组件:

<div>{this.props.myOtherProperty}</div>

您还可以将函数作为属性传递给其他组件,并让它们在需要时回调根组件,如下所示:

<div>
  <child onChange={this.myOnChangeMethodDefinedInRootComponent.bind(this)}></child>
</div>

通过这种方式,您可以“告诉”根组件是否在子组件内部发生了变化而无需使用 Redux

希望这可以帮助

这是您正在查看的内容的快速原型,

将状态从头部组件作为props传递到标签组件。标签组件的变化会修改头部组件的状态并强制重新渲染所有组件。

// Head Component
class HeadCompoent {
  constructor() {
    this.state = {
      password: '',
      userName: '',
    }
  }

  handleFieldChange = (key, val) => {
    this.setState({
      [key]: val,
    });
  };

  render() {
    <Form
      fields={[{
        item: {
          value: this.state.password,
          type: 'password',
          key: 'password'
        },
      }, {
        item: {
          value: this.state.userName,
          type: 'text',
          key: 'userName'
        }
      }]}
      handleFieldChange={this.handleFieldChange} 
    />
  }
}

// Form Component
const Form = (fields) => (
  <div>
    {
      fields.map(p => <Label {...p} />)
    }
  </div>);


// Label Component
const Label = ({ type, value, key, handleFieldChange }) => {
  const handleChange = (key) => (e) => {
    handleFieldChange(key, e.target.value);
  };

  return (
    <input type={type} value={value} key={key} onChange={handleChange(key)} />
  );
};