Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

reactjs - How do I pass props from Child to Parent in React for incremental onClick?


export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      todos: 5
    };
  }

  handleClick = () => {
    this.setState({ todos: this.state.todos + 1 });
  };

  render() {
    return (
      <div className="App">
        <h1>ToDo List</h1>
        <p>Just keep giving me things to do</p>
        <p>I still have {this.state.todos} things to do</p>
        <AddTodo todos={this.state.todos} handleClick={this.handleClick} />
      </div>
    );
  }
}

I am trying to update <p>I still have {this.state.todos} things to do</p> in the Parent to increase by 1 for every button click in the Child Component. What am I missing? I am not getting any errors but it is not functional.

import React from "react";

export default function AddTodo(handleClick) {
  return (
    <div className="AddTodo">
      <button onClick={() => handleClick}>Add Another</button>
    </div>
  );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Props is the first value passed to a functional component, it's an object and you would need to destructure handleClick from it.

export default function AddTodo({ handleClick }) {
  return (
    <div className="AddTodo">
      <button onClick={handleClick}>Add Another</button>
    </div>
  );
}

Also change your handle click function to this

handleClick = () => {
    this.setState(({ todos }) => ({ todos: todos + 1 }));
  };

a working example

const AddTodo = ({ onClick }) => (
  <div className="AddTodo">
    <button onClick={onClick}>Add Another</button>
  </div>
);

const App = () => {
  const [todos, setTodos] = React.useState(5);

  const onClick = () => {
    setTodos((oldTodos) => oldTodos + 1);
  };

  return (
    <div className="App">
      <h1>ToDo List</h1>
      <p>Just keep giving me things to do</p>
      <p>I still have {todos} things to do</p>
      <AddTodo todos={todos} onClick={onClick} />
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://unpkg.com/react@17/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script>
<div id="root"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...