[英]How to pass a function as a prop to React function component?
Im trying to pass a function down as a prop. 我试图传递一个功能作为道具。 Why is this not working?
为什么这不起作用?
In Parent: 在家长中:
const dummyProps = {
label: "Text",
increment: function() {
console.log("+");
},
};
function Parent() {
return (
<div>
<Child {...dummyProps} />
</div>
);
}
In Child: 在儿童中:
function InputNumeric({ label, increment }) {
return(
<label>{label}</label>
<button onClick={increment}>Click</button>
)
}
In React, you need to have a single parent element that is rendered. 在React中,您需要具有一个呈现的单个父元素。 In your question you forgot to wrap the elements inside the child component.
在您的问题中,您忘记将元素包装在子组件内。 You can wrap with another element or with a
React.Fragment
(shorthand syntax is <> </>
) 您可以使用其他元素或
React.Fragment
(简写语法为<> </>
)
function InputNumeric({ label, increment }) {
return(
<>
<label>{label}</label>
<button onClick={increment}>Click</button>
</>
)
}
Remember, 记得,
<div prop1={'asdf'}></div>
is actually translated to 实际上被翻译成
React.createElement('div', {prop1: 'asdf'})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.