简体   繁体   中英

Reactjs Changing the state of another child component

My Parent class has two children

Counter component has state 'counter' which increments by the second;

class Counter extends Component {

    constructor(props) {
        super(props)
        this.resetCount = this.resetCount.bind(this);
        this.state = {
            count : 0
        }
    }

    resetCount() {
        this.setState({
            count : 0
        });
    }

    componentDidMount() {
        setInterval(() => {
            this.setState({
                count: this.state.count + 1
            });
        }, 1000);
    }

    render() {
        const {count} = this.state;
        const {color,size} = this.props;
        return (
            <Text style={{color, fontSize: size}}>{count}</Text>    

            );
    }
}

In the Button Component, I have an onpress thing

  <Button
      onPress={resetCount}
      title="Reset COunt"
      color="#841584"         
    />

In my main Parent Class I render

 <Counter color={'green'} size={90} />
    <Button/>

But I'm getting an error 'can't find variable resetCount' in App.js

You have to use 'this.resetCount' when using 'Button' inside Counter.render()

 <Button
  onPress={this.resetCount}
  title="Reset COunt"
  color="#841584"         
/>

If Button is its own Component as mentioned you have to inherit the function onPress

Component Button

<Button onPress={this.props.onResetCount} ... />

Component Counter

render(){
   return (
            <Text style={{color, fontSize: size}}>{count}</Text>    
            <Button onResetCount={this.resetCount} title="Reset Count" color="... />
            );
   )
}

More detailed: https://reactjs.org/docs/faq-functions.html

This is due to Button not being able to access the class method inside its sibling Counter component. If your reorganise your code a little by moving the shared methods to the parent component you can a) achieve what you want, and b) make your code a little simpler. In other words make Counter the main component made up of two smaller dumb components / pure functions.

// No need for a component, just a function that returns
// a styled div
function Text({ count }) {
  return <div>{count}</div>;
}

// Another function to return a button
function Button({ resetCount, text }) {
  return <button onClick={resetCount}>{text}</button>;
}

// The main component that keeps the state which it passes
// to the dumb Text component
class Counter extends React.Component {

  constructor() {
    super()
    this.state = { count: 0 };
    this.resetCount = this.resetCount.bind(this);
  }

  componentDidMount() {
    setInterval(() => {
      this.setState({
        count: this.state.count + 1
      });
    }, 1000);
  }

  resetCount() {
    this.setState({ count: 0 });
  }

  render() {
    return (
      <div>
        <Text count={this.state.count} />
        <Button resetCount={this.resetCount} text="Reset count" />
      </div>
    )
  }
}


ReactDOM.render(
  <Counter />,
  document.getElementById('container')
);

DEMO

You get the error because you can't do onPress={resetCount} this way. It is searching for the variable. But you don't have a variable, it's a function. So you should use this.resetCount if you want to access the function resetCount() .

Here's an example how you can access the function of your parent component from the button in the child component:

// Parent component:
resetCount() {
  // your code
}
render() {
  return(
    <Button resetCount={this.resetCount} /* your other stuff */ />
  );
}

// Button component:
<button onPress={this.props.resetCount}>Click me</button>

Note: You can't update a sibling this way. You should move your functions from <Counter/> to your parent component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM