Reactjs 在React JSX中,如何将父自定义React组件状态属性值传递给子客户组件?

Reactjs 在React JSX中,如何将父自定义React组件状态属性值传递给子客户组件?,reactjs,Reactjs,在React JSX中,如何将父自定义React组件状态属性值传递给子客户组件 假设MyCustomRectComponentA组件有一个状态变量“offset”。那么,如何访问该组件以作为道具传递给另一个CustomComponentB public render() { return ( <MyCustomRectComponentA> <AnotherCustomComponentB offsetValue={parent.stat

在React JSX中,如何将父自定义React组件状态属性值传递给子客户组件

假设MyCustomRectComponentA组件有一个状态变量“offset”。那么,如何访问该组件以作为道具传递给另一个CustomComponentB

  public render() {
    return (
      <MyCustomRectComponentA>
        <AnotherCustomComponentB offsetValue={parent.state.offset} />
      </MyCustomRectComponentA>
    );

  }
public render(){
返回(
);
}

您可以在
MyCustomRectComponentA
组件中使用
React.Children
React.cloneElement
api

例如:


我们所做的是,我们通过了shubhamkhattri(只是检查一下),JSX摘录实际上来自JSX组件1。在render方法中,我有JSX组件2标记(MyCustomRectComponentA),其中有JSX组件3(另一个CustomComponentB)。所以通常“this”指的是JSX组件1,而不是组件2(/MyCustomRectComponentA)?@shubhamkhattri这不是我们要问的。@DaveNewton我错了,这个问题不太清楚me@Greg是否要访问MyCustomRectComponentA中的偏移量?是@ShubhamKhatri
import React, { Component, Children , cloneElement } from 'react'

class MyCustomRectComponentA extends Component {
    state = {
        offset: '50px'
    }
    render() {
        return (
            <div>              
                // mapping through every children elements
                // passed to "MyCustomRectComponentA" component
                {Children.map(this.props.children, child => { 
                    // you have to clone the child element
                    // because they are read-only 
                    // and pass the "state" as props
                    return cloneElement(child, {
                     offsetValue: this.state.offset 
                    })
                })}
            </div>
        )
    }   
}

export default MyCustomRectComponentA
 public render() {
    return (
      <MyCustomRectComponentA>
        <AnotherCustomComponentB />
      </MyCustomRectComponentA>
    );

  }