Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.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 如何访问和更改child';来自父组件的状态_Javascript_Reactjs_Typescript_React Native - Fatal编程技术网

Javascript 如何访问和更改child';来自父组件的状态

Javascript 如何访问和更改child';来自父组件的状态,javascript,reactjs,typescript,react-native,Javascript,Reactjs,Typescript,React Native,您将获得无法控制的子组件。 父组件存储计数器的数量并呈现该数量的子组件。它有两个按钮“添加计数器”和“增加所有计数器” 不允许您编辑子组件 实施 incrementCounters,使其增加所有子对象的计数器 渲染的组件 递增计数器=()=>{ //TODO:实现 }; 导出类ChildCounter扩展React.Component{ 状态={ 柜台:0 }; 增量=()=>{ this.setState(({counter})=>({ 柜台:柜台+1 })); }; render(){

您将获得无法控制的子组件。 父组件存储计数器的数量并呈现该数量的子组件。它有两个按钮“添加计数器”和“增加所有计数器”

  • 不允许您编辑子组件

  • 实施 incrementCounters,使其增加所有子对象的计数器 渲染的组件

    递增计数器=()=>{ //TODO:实现 };


  • 导出类ChildCounter扩展React.Component{
    状态={
    柜台:0
    };
    增量=()=>{
    this.setState(({counter})=>({
    柜台:柜台+1
    }));
    };
    render(){
    返回(
    计数器:{this.state.Counter}
    +
    );
    }
    }
    

    从“/Child”导入{ChildCounter};
    类应用程序扩展了React.Component{
    状态={计数器:1}
    addCounter=()=>{
    让countern=this.state.counters+1;
    this.setState({counters:countern})
    };
    递增全部=()=>{
    }
    render(){
    返回(
    {新数组(this.state.counters).fill(0).map((\u,index)=>{
    返回;
    })
    }
    
    添加计数器 递增所有计数器 ) } }
    首先,我不知道你为什么不想用state来做,我认为这样会更好 通过使用计数器值数组,然后一次递增所有计数器值,并将子组件作为控制器组件

    对于裁判,我没能想出一个好的解决方案(不确定)。 因此,我在这里传递了代码,我所做的是,我使用了一个名为
    useImperialiveHandle
    的react钩子,让您的子组件获取ref并公开内部
    increment
    方法。 然后我在父组件中添加了一个引用数组。 因此,当用户单击“全部递增”时,基本上就是循环引用并调用内部递增方法。 我仍然不确定实现ref数组的正确方法,但我认为应该这样做。 我已经用钩子写了这篇文章,让它更容易理解

    
    import React, {
      useState,
      useEffect,
      createRef,
      forwardRef,
      useImperativeHandle
    } from "react";
    
    const ChildCounter = forwardRef((props, ref) => {
      const [counter, setCounter] = useState(0);
    
      const increment = () => {
        setCounter((c) => c + 1);
      };
    
      useImperativeHandle(ref, () => ({
        increment
      }));
    
      return (
        <div>
          Counter: {counter}
          <button onClick={increment}>+</button>
        </div>
      );
    });
    
    const App = () => {
      const [counters, setCounters] = useState(1);
      const [elRefs, setElRefs] = useState([]);
    
      const addCounter = () => {
        setCounters((c) => c + 1);
      };
    
      useEffect(() => {
        setElRefs((elRefs) =>
          Array(counters)
            .fill()
            .map((_, i) => elRefs[i] || createRef())
        );
      }, [counters]);
    
      const incrementAll = () => {
        for (let i = 0; i < elRefs.length; i++) {
          if (elRefs[i] && elRefs[i].current) {
            elRefs[i].current.increment();
          }
        }
      };
    
      return (
        <div>
          {new Array(counters).fill(0).map((_, index) => {
            return <ChildCounter ref={elRefs[index]} key={index} />;
          })}
          <br />
          <button style={{ marginRight: 10 }} onClick={addCounter}>
            Add Counter
          </button>
          <button onClick={incrementAll}>Increment all counters</button>
        </div>
      );
    };
    
    export default App;
    
    
    
    进口反应{
    useState,
    使用效果,
    createRef,
    forwardRef,
    使用命令式处理
    }从“反应”;
    const ChildCounter=forwardRef((道具,ref)=>{
    const[counter,setCounter]=useState(0);
    常量增量=()=>{
    设置计数器((c)=>c+1);
    };
    使用命令式句柄(参考,()=>({
    增量
    }));
    返回(
    计数器:{Counter}
    +
    );
    });
    常量应用=()=>{
    常量[计数器,设置计数器]=使用状态(1);
    const[elRefs,setElRefs]=useState([]);
    常量addCounter=()=>{
    设置计数器((c)=>c+1);
    };
    useffect(()=>{
    setElRefs((elRefs)=>
    阵列(计数器)
    .fill()
    .map((_,i)=>elRefs[i]| | createRef())
    );
    },[柜台];
    常量递增全部=()=>{
    for(设i=0;i{
    返回;
    })}
    
    添加计数器 递增所有计数器 ); }; 导出默认应用程序;

    首先,我不知道你为什么不想用国家来做,我认为这样会更好 通过使用计数器值数组,然后一次递增所有计数器值,并将子组件作为控制器组件

    对于裁判,我没能想出一个好的解决方案(不确定)。 因此,我在这里传递了代码,我所做的是,我使用了一个名为
    useImperialiveHandle
    的react钩子,让您的子组件获取ref并公开内部
    increment
    方法。 然后我在父组件中添加了一个引用数组。 因此,当用户单击“全部递增”时,基本上就是循环引用并调用内部递增方法。 我仍然不确定实现ref数组的正确方法,但我认为应该这样做。 我已经用钩子写了这篇文章,让它更容易理解

    
    import React, {
      useState,
      useEffect,
      createRef,
      forwardRef,
      useImperativeHandle
    } from "react";
    
    const ChildCounter = forwardRef((props, ref) => {
      const [counter, setCounter] = useState(0);
    
      const increment = () => {
        setCounter((c) => c + 1);
      };
    
      useImperativeHandle(ref, () => ({
        increment
      }));
    
      return (
        <div>
          Counter: {counter}
          <button onClick={increment}>+</button>
        </div>
      );
    });
    
    const App = () => {
      const [counters, setCounters] = useState(1);
      const [elRefs, setElRefs] = useState([]);
    
      const addCounter = () => {
        setCounters((c) => c + 1);
      };
    
      useEffect(() => {
        setElRefs((elRefs) =>
          Array(counters)
            .fill()
            .map((_, i) => elRefs[i] || createRef())
        );
      }, [counters]);
    
      const incrementAll = () => {
        for (let i = 0; i < elRefs.length; i++) {
          if (elRefs[i] && elRefs[i].current) {
            elRefs[i].current.increment();
          }
        }
      };
    
      return (
        <div>
          {new Array(counters).fill(0).map((_, index) => {
            return <ChildCounter ref={elRefs[index]} key={index} />;
          })}
          <br />
          <button style={{ marginRight: 10 }} onClick={addCounter}>
            Add Counter
          </button>
          <button onClick={incrementAll}>Increment all counters</button>
        </div>
      );
    };
    
    export default App;
    
    
    
    进口反应{
    useState,
    使用效果,
    createRef,
    forwardRef,
    使用命令式处理
    }从“反应”;
    const ChildCounter=forwardRef((道具,ref)=>{
    const[counter,setCounter]=useState(0);
    常量增量=()=>{
    设置计数器((c)=>c+1);
    };
    使用命令式句柄(参考,()=>({
    增量
    }));
    返回(
    计数器:{Counter}
    +
    );
    });
    常量应用=()=>{
    常量[计数器,设置计数器]=使用状态(1);
    const[elRefs,setElRefs]=useState([]);
    常量addCounter=()=>{
    设置计数器((c)=>c+1);
    };
    useffect(()=>{
    setElRefs((elRefs)=>
    阵列(计数器)
    .fill()
    .map((_,i)=>elRefs[i]| | createRef())
    );
    },[柜台];
    常量递增全部=()=>{
    for(设i=0;i{
    返回;
    })}
    
    添加计数器 递增所有计数器 ); }; 导出默认应用程序;
    这在技术上是可以实现的,而无需更改子级,方法是从父级传递一个ref,并让父级在调用
    incrementAll
    时使用ref访问子级上的
    increment
    方法:

    childCounterChildren = [];
    
    incrementAll = () => {
        for (const counter of this.childCounterChildren) {
            counter.increment();
        }
    }
    
    {if(childCounter){this.childCounter.push(childCounter);}}
    />;
    
    类ChildCounter扩展React.Component{
    状态={
    柜台:0
    };
    增量=()=>{
    this.setState(({counter})=>({
    柜台:柜台+1
    }));
    };
    render(){
    返回(
    
    childCounterChildren = [];
    
    incrementAll = () => {
        for (const counter of this.childCounterChildren) {
            counter.increment();
        }
    }
    
    <ChildCounter
        key={index}
        ref={(childCounter) => { if (childCounter) { this.childCounterChildren.push(childCounter); }}}
    />;