简体   繁体   English

如何从父组件访问嵌套组件?

[英]How can I accessing nested component in react from parent component?

I want to access a nested component from parent component.我想从父组件访问嵌套组件。

This is Bill Form.jsx这是比尔 Form.jsx

      import BillDetailForm from './BillDetailForm';


         render(){

          return (
            <form onSubmit={handleSubmit}>

             <FieldArray

               name= 'detail'
               component={BillDetailForm}
               placeholder= '...detail'
               label='Detail'

                 />
               </form>
                  );
                   }
               }

BillForm is the parent component. BillForm 是父组件。

This is a nested component or child component of BillForm: BillDetailForm.jsx这是 BillForm 的嵌套组件或子组件:BillDetailForm.jsx

     render(){


    return(
         <form onSubmit={ handleSubmit }>


       <div>Detail:</div>
      <FieldArray
        name= 'detail'
        component={RenderDetail}
        label='Detail'
      />

      </form>

    )

} 

Inside BillDetailForm is RenderDetail: BillDetailForm 里面是 RenderDetail:

        const RenderDetail = ({fields, meta: { error,submitFailed}},props) => (
          <dl>
         <dt>
            <button type="button" className= 'btn btn-primary' onClick={() => fields.push()}>Add 
        Detail</button>
             {submitFailed && error && <span>{error}</span>}
           </dt>
               { fields.map((registerDetail, index) =>
               //In the following line renderDetail is accesing Detail component.
               <Detail detailItem={registerDetail} fields={fields} index={index} key={index}/>

               )
             }

            {error && <dt className="error">{error}</dt>}
            </dl> 
            );

This is Detail Class Component:这是细节类组件:

          class Detail extends Component{

                   render(){

                   const{detailItem,index,fields,isSubtotal} = this.props;

                        return(


                    <dd key={index}>
                    <br></br>
                    <button className= 'btn btn-light mr-2'
                     type="button"
                     title="Remove detail"
                     onClick={() => { fields.remove(index)
                      if(fields.length == 0 || fields.length === undefined){

                        }
                      try{
                     for(let x in fields){
                     fields.remove(index) 
                     let d = fields.selectedIndex;
                    if(fields.remove(index) && d >= 1 && d< fields.length ){
                    fields.removeAll(index);
                     }
                     }
                  }catch{console.info("deletes non numerical index")}

                      }}> Delete </button>

              <h4>DetailRegister #{index + 1}</h4>

               <Field 
                 id={`${detailItem}._id`}
                 name={`${detailItem}.quantity`}
                 component= {NumberPickerInteger}
                 placeholder= '...quantity'
                 label = "Quantity" 
                  />
          <br></br>
          <h3><b>Product</b></h3>
               <Field 
                id={`${detailItem}._id`}
                name={`${detailItem}.product.code`}
                type="number"
                component= {RenderFieldNumeric}
                placeholder='...Product's code'
               label = "Product's code" 
             />
          <Field 
           id={`${detailItem}._id`}
           name={`${detailItem}.product.name`}
           type="text"
           component= {RenderField}
           placeholder='...Product's name'
           label = "Product's name" 
         />
            <Field 
              id={`${detailItem}._id`}
              name={`${detailItem}.product.price`}
              component= {NumberPickerr}
              placeholder= '...Price'
              label = "Product's price" 
             />
         <br></br>
      <h3><b>Subtotal</b></h3>
       <Field 
          id={`${detailItem}._id`}
          name={`${detailItem}.subtotal`}
          component= {SubtotalWidget}
          placeholder= '...subtotal'
          label = "Subtotal" 
           >
            {isSubtotal}
             </Field>



            </dd>

            );

          }
       }

I want to access eg ${props.detailItem}.subtotal that is in Detail from BillForm.我想从 BillForm 中访问例如${props.detailItem}.subtotal详细信息。 BillForm accesses to BillDetailForm, BillDetailForm accesses to renderDetail, and last renderDetail acceses to Detail. BillForm 访问BillDetailForm,BillDetailForm 访问renderDetail,最后renderDetail 访问Detail。

The question is: How can I access and use props like quantity and subtotal with dynamic index (props.index) from BillForm?问题是:如何从 BillForm 访问和使用带有动态索引 (props.index) 的数量和小计等道具? I want to access Detail component from BillForm, respecting the following secuence in order access: BillForm -> BillDetailForm -> RenderDetail -> Detail我想从 BillForm 访问 Detail 组件,在访问顺序中遵循以下顺序:BillForm -> BillDetailForm -> RenderDetail -> Detail

If I understand correctly what you are saying, it seems you are going against the ethos of React.如果我正确理解您的意思,那么您似乎违背了 React 的精神。 If your parent component wants access to a piece of data, then that data should start in the parent and be passed down.如果您的父组件想要访问一段数据,那么该数据应该从父组件开始并向下传递。 This way, if the data changes it will call a re-render of components and update all necessary components.这样,如果数据发生变化,它将调用组件的重新渲染并更新所有必要的组件。

Some other advice.其他一些建议。 Try not o have so much logic inside your component handlers, it looks messy and will run every render cycle.尽量不要在你的组件处理程序中有这么多的逻辑,它看起来很混乱并且会在每个渲染周期运行。 Abstract this into a method on the class and call it when required.将此抽象为类上的一个方法,并在需要时调用它。

My example will hopefully help you with your issue, but I recommend having a read of the React documentation as it is very good with simple examples.我的示例有望帮助您解决问题,但我建议您阅读 React 文档,因为它非常适合简单示例。 The use of class will be deprecated eventually in favour of function components and the Hooks API.类的使用最终将被弃用,取而代之的是函数组件和 Hooks API。

class ParentComponent {
  state = {
    value: 0,
  }

  methodToDoSomething = (passedVal) => {
    this.setState({
      value: passVal,
    });
  }

  render() {
    const myState = this.state;
    return (
     <Component {...myState} />
    )
  }
}

class Component {
  state = {}

  render() {
    const { value , methodToDoSomething } = this.props;
    return (
     <div onClick={methodToDoSomething}>
      {value}
     </div>
    )
  }
}

// Hooks API

const ParentComponent = () => {

  const [stateVal, updateState] = React.useState('myString');

  return (
    <div>
      {stateVal}
      <Component passedVal={stateVal} passedHandler={updateState} />
    </div>
  )
}

const Component = ({ stateVal, passedHandler }) => {

  function updateMyValue() {
    passedHandler('menewvalue');
  }

  return (
    <div onClick={updateMyValue}>
     {stateValue}
    <div/>
  )
}

To avoid passing lots down all the children components, I would recommend reading up on the Context Hook.为了避免大量传递给所有子组件,我建议阅读上下文挂钩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 React 中的父组件调用子 function - How can I call Child function from Parent Component in React 如何从嵌套组件调用 React 中的“useSate(false)”? - How can I call "useSate(false)" in React from a nested component? 从父级访问反应组件的属性 - Accessing properties of a react component from the parent 从父级访问 React 组件子级道具 - Accessing React component children props from the parent 如何在React中将多个数据作为对象从子组件发送到父组件? - How can i send multiple data as an object to parent component from child component in React? 在 REACT.js 中,如何将状态从子组件传递到父组件作为道具 - In REACT.js how can I pass a state from child component up to Parent component as a prop React - 如何从父组件内的 function 制作组件? - React - How can I make a component from a function inside a parent component? 如何通过道具[REACT.JS]将图片网址从父组件传递到子组件 - How can I pass image url from parent component to child component via props [REACT.JS] React:如何将嵌套子组件中的元素传递给嵌套父组件 - React : How to pass an element in nested child component to nested parent component 在Meteor + React中,如何在父React组件中渲染子React组件? - in Meteor+React, how can i render a child React component in a parent React component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM