javascript 将onClick函数作为props传递给子组件

y4ekin9u  于 2023-01-04  发布在  Java
关注(0)|答案(6)|浏览(210)

我有一个handelSubmit函数,它是后端的post数据。现在我想把这个函数作为一个prop传递给子组件,但是我收到了警告。我该如何处理这个问题?
这是我需要传入父组件的函数

const handleSubmit = (e) => {
    e.preventDefault();
    request(JSON.stringify(staff));
  };


 <SubmitButton
   loading={loading}
   formValid={errMessage.formValid}
   handleSubmit={handleSubmit}
  />

子元件

function SubmitButton(formValid, isActive, handleSubmit, loading) {
return(
 <button
   className={formValid ? `submit ${false ? "active" : " "}` : "disable"}
   type="button"
   onClick={() => handleSubmit()}      ***//how can I solve here?***
   disabled={!formValid}
    > <span>Submit</span>
</button>
)
    }
mrzz3bfm

mrzz3bfm1#

您没有正确使用 prop ,您忘记了{}
function SubmitButton({formValid, isActive, handleSubmit, loading})

smtd7mpg

smtd7mpg2#

尝试在OnClick eventHandler中传递事件参数

onClick = {(e) => handleSubmit(e)}
vaqhlq81

vaqhlq813#

问题是组件只接收一个名为props的参数,如果您试图对其进行反结构化,应该使用括号{}将prop值封装在SubmitButton中,如下所示

function SubmitButton({formValid, isActive, handleSubmit, loading}) {
   return ...
}

或者

function SubmitButton(props) {
   const { formValid, isActive, handleSubmit, loading } = props  

   return ...
}
7kjnsjlb

7kjnsjlb4#

您将props定义为SubmitButton的参数。但请记住,props是传递给react组件的单个参数。您需要像这样从props进行反结构:

function SubmitButton({ formValid, isActive, handleSubmit, loading }) {
    return (
        <button
            className={formValid ? `submit ${false ? 'active' : ' '}` : 'disable'}
            type="button"
            onClick={() => handleSubmit()}
            disabled={!formValid}
        >
            <span>Submit</span>
        </button>
    );
}
2vuwiymt

2vuwiymt5#

将其包含在onClick属性的值中,如下所示:

<SubmitButton
  loading={loading}
  formValid={errMessage.formValid}
  handleSubmit={handleSubmit}
/>

<button
  className={formValid ? `submit ${false ? "active" : " "}` : "disable"}
  type="button"
  onClick={handleSubmit}
  disabled={!formValid}
>
  <span>Submit</span>
</button>
rkkpypqq

rkkpypqq6#

你可以试着破坏这些 prop

function SubmitButton({formValid, isActive, handleSubmit, loading}) {
 
}

相关问题