猿问

如何将 HTML 属性传递给 React 中的子组件?

我有一个父组件和一个子组件,子组件有一个按钮,我想在第一次单击后禁用它。这个答案在子组件中对我有用。但是点击时执行的函数现在存在于父组件中,我如何将属性传递给子组件?我尝试了以下但没有用。


家长:


const Home = () => {

  let btnRef = useRef();

  const handleBtnClick = () => {

    if (btnRef.current) {

        btnRef.current.setAttribute("disabled", "disabled");

    }

  }

  

  return (

    <>

      <Card btnRef={btnRef} handleBtnClick={handleBtnClick} />

    </>

  )

}

孩子:


const Card = ({btnRef, handleBtnClick}) => {

  return (

    <div>

      <button ref={btnRef} onClick={handleBtnClick}>Click me</button>

    </div>

  )

}


陪伴而非守候
浏览 186回答 3
3回答

小怪兽爱吃肉

一般来说,refs 应该只作为 React 中的最后手段使用。React 本质上是声明式的,所以与其让父级“让”子级禁用(这就是你对 ref 所做的),不如说它应该“说”子级应该被禁用(如下例):const Home = () => {&nbsp; const [isButtonDisabled, setIsButtonDisabled] = useState(false)&nbsp; const handleButtonClick = () => {&nbsp; &nbsp; setIsButtonDisabled(true)&nbsp; }&nbsp;&nbsp;&nbsp; return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; <Card isDisabled={isButtonDisabled} onButtonClick={handleButtonClick} />&nbsp; &nbsp; </>&nbsp; )}const Card = ({isDisabled, onButtonClick}) => {&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <button disabled={isDisabled} onClick={onButtonClick}>Click me</button>&nbsp; &nbsp; </div>&nbsp; )}

临摹微笑

实际上,如果您修复Card组件中的拼写错误,它就会起作用。只需重命名hadnlBtnClick为handleBtnClick

慕神8447489

您不需要按名称提及每个道具/属性,因为您可以Object Destructuring在此处使用 javascript。const Home = () => {&nbsp; const [isButtonDisabled, setIsButtonDisabled] = useState(false)&nbsp; const handleButtonClick = () => {&nbsp; &nbsp; setIsButtonDisabled(true)&nbsp; }&nbsp;&nbsp;&nbsp; return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; <Card isDisabled={isButtonDisabled} onButtonClick={handleButtonClick} />&nbsp; &nbsp; </>&nbsp; )}const Card = (props) => {&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <button {...props}>Click me</button>&nbsp; &nbsp; </div>&nbsp; )}您还可以选择一些道具,并在子组件中以不同的方式使用它们。例如,请参见text下面的道具。const Home = () => {&nbsp; const [isButtonDisabled, setIsButtonDisabled] = useState(false)&nbsp; const handleButtonClick = () => {&nbsp; &nbsp; setIsButtonDisabled(true)&nbsp; }&nbsp;&nbsp;&nbsp; return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; <Card text="I'm a Card" isDisabled={isButtonDisabled} onButtonClick={handleButtonClick} />&nbsp; &nbsp; </>&nbsp; )}const Card = ({text, ...restProps}) => {&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <button {...restProps}>{text}</button>&nbsp; &nbsp; </div>&nbsp; )}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答