Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 子组件中父组件的访问状态?_Javascript_Reactjs_Ecmascript 6_State_React Props - Fatal编程技术网

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

Javascript 子组件中父组件的访问状态?,javascript,reactjs,ecmascript-6,state,react-props,Javascript,Reactjs,Ecmascript 6,State,React Props,我是react js新手,我需要获取组件的状态以供另一个类访问,我遇到了这个问题,因为我使用原子设计,因为在一个组件中编写所有内容都变成了一个问题,下面是我的代码: 头部组件: class Headcomponent extends React.Component{ constructor (props) { super(props); this.state = { email: '', password: '', formErrors

我是react js新手,我需要获取组件的状态以供另一个类访问,我遇到了这个问题,因为我使用原子设计,因为在一个组件中编写所有内容都变成了一个问题,下面是我的代码: 头部组件

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;
类头组件扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
电子邮件:“”,
密码:“”,
formErrors:{电子邮件:'',密码:'},
emailValid:false,
passwordValid:false,
formValid:false,
项目:[],
}
}
this.setState({formErrors:fieldValidationErrors,
emailValid:emailValid,
passwordValid:passwordValid
},this.validateForm);
}
validateForm(){
this.setState({formValid:this.state.emailValid&&
this.state.passwordValid});
}
render(){
返回(
);
}
}
Headcomponent.propTypes={
形式:PropTypes.array,
};
Headcomponent.defaultProps={
表格:[
{
标签:“label1”,
占位符:“输入1”,
},
{
标签:“label2”,
占位符:“输入2的占位符”,
},
],
};
导出默认Headcomponent;
form.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;
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"
      />
    );
  }
}
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>
 );
 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>
 );
const Form=props=>(
{
props.fields.map((field,i)=>())
}
);
Form.propTypes={
字段:PropTypes.arrayOf(PropTypes.object).isRequired,
buttonText:PropTypes.string.isRequired,
};
导出默认表单;
LabeledInput.js(在这里我需要传递密码的状态)

const LabeledInput=props=>(
{props.errorMessage}
{props.exampleText}
);
LabeledInput.propTypes={
标签:PropTypes.string.isRequired,
占位符:PropTypes.string,
onChange:PropTypes.func.required,
值:PropTypes.string.isRequired,
exampleText:PropTypes.string,
errorMessage:PropTypes.string,
};
导出默认标签输入;

如何在
labelledinput
中访问headComponent的状态?

导出默认headComponent
,然后
导入它内部
LabelledInout

这是头部组件

export default class Headcomponent extends React.Component{ 
  ...
}
标号输入元件

 import Headcomponet from './headComponent.js'

 const LabelledInput = (props) => {
    return(<Headcomponent />);
 }
从“./headComponent.js”导入Headcomponet
常量标签输入=(道具)=>{
return();
}

您可以使用
道具来实现这一点

根组件:

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

子组件:

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

第1部分:

<div>
  <child myState="hello"></child>
</div>
<div>
  <child2 myOtherProperty={this.props.myState}></child2>
</div>
<div>{this.props.myOtherProperty}</div>
{this.props.myOtherProperty}
您还可以将函数作为属性传递给其他组件,并允许它们在需要时回调根组件,如:

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

通过这种方式,您可以在不使用
Redux


希望这有帮助这里有一个快速的原型

将状态作为道具从头部组件传递到标签组件。标签组件中的更改将修改头部组件的状态,并强制重新渲染所有组件

// 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)} />
  );
};
//头部组件
班主任{
构造函数(){
此.state={
密码:“”,
用户名:“”,
}
}
handleFieldChange=(键,值)=>{
这是我的国家({
[钥匙]:瓦尔,
});
};
render(){
}
}
//表单组件
常量形式=(字段)=>(
{
fields.map(p=>)
}
);
//标签组件
常量标签=({type,value,key,handleFieldChange})=>{
常量handleChange=(键)=>(e)=>{
handleFieldChange(键,即目标值);
};
返回(
);
};

最合理的方法是将其作为道具传递(您需要的
头部组件的状态值):

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;
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"
      />
    );
  }
}
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>
 );
 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>
 );
类头组件扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
电子邮件:“”,
密码:“”,
formErrors:{电子邮件:'',密码:'},
emailValid:false,
passwordValid:false,
formValid:false,
项目:[],
}
}
render(){
返回(
))
}
);
LabeledInput.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;
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"
      />
    );
  }
}
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>
 );
 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>
 );
const LabeledInput=props=>(
{props.formValid&&“此表单有效”}//来自Headcomponent的状态
{props.errorMessage}
{props.exampleText}
);

因此,如果任何时候
Headcomponent
的状态被更新,它将被传播到
LabeledInput
组件这是访问
LabeledInput
Headcomponent
的状态的最简单方法,以保持向下传递

如果要从
headComponent
内部
LabeledInput
访问值
this.state.password
,则将此
this.state.password
作为属性传递给呈现方法中的表单组件

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

然后,通过调用
This.props.password

,您可以访问
LabeledInput
组件内的值,以及如何获取对组件正确实例的引用?您必须创建该实例,然后创建访问该状态的方法。您不能直接引用该状态,即cr组件的eation由
react
@messerbill处理,以获取您创建的用于存储实例的变量的实例。例如
const head=new headComponent()
然后您可以访问实例上的类方法。但是,如果您只需要使用类而不需要使用组件方法,为什么要扩展组件类?可能的重复项将headComponent的状态作为道具传递到form component,然后传递到labelledcomponent。如果组件完全不相关,则需要使用redux负责管理该州。如果我的回答回答了你的问题,请接受回答。如果你是st