类型错误:“onChange 不是函数”

时间:2021-06-25 18:56:54

标签: javascript reactjs

我正在尝试从子组件更改父组件的状态值,但出现 onChange is not a function 错误。我已经尝试了我找到的所有解决方案,但没有任何帮助。

这是父组件的代码:

const [playerCount, setPlayerCount] = useState(0);
  const handleChange = (newValue) => {
    setPlayerCount(newValue);
  }

  return (
    <div className="App">
      <Question question={question}/>

      {renderBoard()}

      <div className="players">
        {players}
      </div>

      <div>
        {!isBetted && allPlayersAnswered? <Bid color={playerColors[playerCount]} playerCount={playerCount} onChange={handleChange}></Bid> : ''}
      </div>
    </div>
  );

这是 Bid.js - 子组件:

import React from 'react'

const Bid = (color,playerCount, onChange) => {
    const handleChange = () => {
        onChange(playerCount+1);
    }
    
    return (
        <button onClick={handleChange}>Click Me</button>
    )
}

export default Bid

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

组件的 props 是一个对象,因此您需要这样传递它:

Bid = ({ color, playerCount, onChange })