reactjs 如何重置子元素的状态?

pkmbmrz7  于 2023-03-08  发布在  React
关注(0)|答案(4)|浏览(163)

假设我有三个元素,它们在状态中保存一个计数器,当被单击时,计数器递增。
如果我单击一个元素,如何将其他计数器重置为0?
https://jsfiddle.net/69z2wepo/56827

const Parent = React.createClass({
    render() {
        const rows = [];
        for (let i = 0; i < 3; i++) {
            rows.push(<Child key={i} />);
        }
        return (
            <ul>
                {rows}
            </ul>
        );
    }
});

const Child = React.createClass({
    getInitialState() {
        return {counter: 0};
    },
    handleClick() {
        this.setState({counter: ++this.state.counter });
    },
    render() {
        return (
            <div onClick={this.handleClick}>
                {this.state.counter}
            </div>
        );
    }
});

ReactDOM.render(
    <Parent />,
    document.getElementById('app')
);
wqsoz72f

wqsoz72f1#

如果你真的不能像其他答案所建议的那样将lift the state安装到父组件中,那么一个很有技巧的方法就是改变一个元素的key属性,这会导致React卸载旧的key元素,并安装一个新的示例。

class ChildComponent extends React.Component {
  state = {
    count: 0
  };
  render() {
    const { count } = this.state;
    return (
      <div>
        <div>count: {count}</div>
        <button onClick={() => this.setState({ count: count + 1 })}>Increment</button>
      </div>
    );
  }
}

class ParentComponent extends React.Component {
  state = {
    stateBustingKey: 0
  };
  render() {
    const { stateBustingKey } = this.state;
    return (
      <div>
        <ChildComponent key={stateBustingKey} />
        <button
          onClick={() =>
            this.setState({ stateBustingKey: stateBustingKey + 1 })
          }
        >
          Reset
        </button>
      </div>
    );
  }
}

ReactDOM.render(<ParentComponent />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root" />
6rvt4ljy

6rvt4ljy2#

这可能有点困难,因为Child组件管理它们自己的状态。
您可以将它们转换为哑组件,并在Parent组件中管理它们的状态。
就像这样

const Parent = React.createClass({
    getInitialState() {
        return {counters: [0,0,0]};
    },
    handleClick(index){
       let newCounterState = this.state.counters.map(() => 0);
       newCounterState[index] = this.state.counters[index] + 1 ;
       this.setState({counters : newCounterState})
    },
    render() {
        const rows = this.state.counters.map((value,index) => (
            <Child 
               key={index}
               handleClick={() => this.handleClick(index)}
               counter={value}
            />
        ))
        return (
            <ul>
                {rows}
            </ul>
        );
    }
});

const Child = ({counter,handleClick}) => (
    <div onClick={handleClick}>
      {counter}
  </div>
)

ReactDOM.render(
    <Parent />,
    document.getElementById('app')
);

jsfiddle

v8wbuo2f

v8wbuo2f3#

在这种情况下,组件parent应按照children的状态进行管理。
检查以下内容:

const Parent = React.createClass({
    getInitialState() {
        return {counter: 0, id: 0};
    },
    handleClick(id) {
        if(this.state.id == id){
            this.setState({counter: ++this.state.counter, id: id });
        } else {
            this.setState({counter: 1, id: id });   
        }

    },
    getCounter(id){
        if(id == this.state.id){
            return this.state.counter;
        } else {
            return 0;
        }
    },
    render() {
        const rows = [];
        for (let i = 0; i < 3; i++) {
            rows.push(<Child key={i} counter={this.getCounter(i)} handleClick={this.handleClick} id={i} />);
        }
        return (
            <ul>
                {rows}
            </ul>
        );
    }
});

const Child = React.createClass({

    render() {
        return (
            <div onClick={this.props.handleClick.bind(null, this.props.id)}>
                {this.props.counter}
            </div>
        );
    }
});

ReactDOM.render(
    <Parent />,
    document.getElementById('app')
);

JsFiddle

nkoocmlb

nkoocmlb4#

const Parent = () => {
   let clearFunc = null; // child clear state function will be stored in this variable
   // in parent component, call this clearChild function.
   const clearChild = () => {
     typeof childClearFunc === 'function' && childClearFunc();
   }
   return <Child handleClear={(func) => clearFunc = func } />
}
const Child = () => {
  const handleClear = () => {
    // code to clear everything in child
  };

  if (props.handleClear) {
    props.handleClear(handleClear);
  }
}

相关问题