简体   繁体   English

当我有多个子组件时,如何将值从子组件传递给父组件?

[英]How could i pass a value from a child component to parent, when i have multiple child components?

I creat multiple components, they have the same hierarchy, and inside they i also call other component call, now i want to create functions on my which will update the values i'm passing as props to my component.我创建了多个组件,它们具有相同的层次结构,并且在它们内部我还调用了其他组件调用,现在我想在我的组件上创建函数,它将更新我作为道具传递给组件的值。 I manage to pass the functions as props, but can't manage to pass the value from child as parameters to the functions, so i could update only the props especific to that child.我设法将函数作为道具传递,但无法将孩子的值作为参数传递给函数,因此我只能更新特定于该孩子的道具。

App应用程序


function App() {
  // eslint-disable-next-line
  const [content, setContent] = useState(images)
  const [count, setCount] = useState(content.votes)

  console.log(count)

  const upVote = (id) => {
    alert('up =>', id)
  }

  const downVote = () => {
    alert('down')
  }

  return (
    <div className="App">
      <div className="grid">
        {content.map((picture, index) => {
          return <Card key={index} picture={picture} teste={[upVote, downVote]}/>
          })
        }
      </div>
    </div>
  )
}

Card卡片

function Card({ picture, teste }) {

  return (
    <div className="card">
      <div className="container">
        <img
          width="300"
          alt={`id: ${picture.id}`}
          src={picture.src}
          className="image"
        />
        <Options votes={0} originalPost={picture.original_post} teste={teste[0]}/>
      </div>
    </div>
  )
}

Options选项

function Options({ votes, originalPost, teste }) {

  const [count, setCount] = useState(votes)
  const [styling, setStyling] = useState('#696969')

  function countStyle(count) {
    if (count > 0){
      setStyling('#008000')
    } else if (count < 0) {
      setStyling('#B22222')
    } else {
      setStyling('#696969')
    }
  }

  return (
    <div>
      <button onClick={() => teste(count)} className="buttons">teste</button>        
      <button title="Down vote" onClick={() => { 
        setCount(count - 1)
        countStyle(count-1)
        // style(count - 1)
      }} className="buttons">-</button>

      <span title="Vote counter" style={{color: styling}} className="counter">{count}</span>

      <button title="Up vote" onClick={() => {
        setCount(count + 1)
        // style(count + 1)
        countStyle(count +1)
      }} className="buttons">+</button><br></br>

      <a href={originalPost} 
        target="_blank"
        title="Click to check the original post"
        rel="noopener noreferrer"
        className="link">Original post</a>
    </div>
  )
}

I would start by consolidating your state into the App component.我首先将您的 state 合并到 App 组件中。 Save the votes on your content array on each picture object.将投票保存在每张图片 object 上的内容数组上。 Pass the upvote and downvote functions down to each children and call them from your button clicks.将 upvote 和 downvote 功能传递给每个孩子,并通过您的按钮点击调用他们。 I would also calculate the styling based on the props, rather than use state.我还会根据道具计算样式,而不是使用 state。

App应用程序

function App() {
  let initialstate = images.map(image => {
    image.votes = 0;
    return image;
  });

  const [content, setContent] = useState(initialstate);

  const upVote = index => {
    setContent(content[index].votes + 1);
  };

  const downVote = index => {
    setContent(content[index].votes - 1);
  };

  return (
    <div className="App">
      <div className="grid">
        {content.map((picture, index) => {
          return <Card key={index} picture={picture} index={index} upVote={upVote} downVote={downVote} />;
        })}
      </div>
    </div>
  );
}

Card卡片

function Card({ index, picture, ...props }) {
  const upVote = () => props.upVote(index);
  const downVote = () => props.downVote(index);

  return (
    <div className="card">
      <div className="container">
        <img
          width="300"
          alt={`id: ${picture.id}`}
          src={picture.src}
          className="image"
        />
        <Options votes={picture.votes} originalPost={picture.original_post} upVote={upVote} downVote={downVote}/>
      </div>
    </div>
  )

Options选项

function Options({ votes, originalPost, upVote, downVote }) {
  let styling = '#696969';

  if (count > 0) {
    styling = '#008000';
  } else if (count < 0) {
    styling = '#B22222';
  } else {
    styling = '#696969';
  }

  return (
    <div>
      <button title="Down vote" onClick={downVote} className="buttons">
        -
      </button>

      <span title="Vote counter" style={{ color: styling }} className="counter">
        {votes}
      </span>

      <button title="Up vote" onClick={upVote} className="buttons">
        +
      </button>
      <br></br>

      <a
        href={originalPost}
        target="_blank"
        title="Click to check the original post"
        rel="noopener noreferrer"
        className="link"
      >
        Original post
      </a>
    </div>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将组件从父级传递给 chlid,而子级将字段传递给组件? - How do I pass in component from parent to chlid and the child pass in field to the components? 当我通过 props 从父组件将变量的值传递给子组件时,我收到一个未定义的值 - I receive an undefined value when I pass the value of a variable through props from a parent component to a child component 如何在 Angular 中将组件从父组件复制并传递给子组件? - how can i copy and pass components from a parent to a child component in Angular? 我将如何将来自多个子组件的表单输入绑定到父组件中定义的数组? - How would I go about binding form input from multiple child components to an array defined in a parent component? 如何使用 function 将值从子组件传递到父组件? - How do i pass a value from child component to parent component using function? 如何动态添加父组件时,如何访问父组件的子组件值? - How can I access child components values from a parent component when they are added dynamically? 如何将状态从这个子组件传递给父组件? - How can I pass the state from this child to parent component? 使用 React Hooks,当我将 prop 从父组件传递给子组件时,子组件中的 prop 未定义 - Using React Hooks, when I pass down a prop from parent to a child component, the prop in the child component is undefined 如何将值从父组件传递给子组件(反应) - How to pass value from parent component to child component (react) 如何将值从子功能组件传递给父类组件? - How to pass value from a child functional component to parent class component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM