[英]Pass value to a given function prop React
This questions may already exist, if so link off to it and I can close this.这个问题可能已经存在,如果有的话,链接到它,我可以关闭它。 Could not find an answer or proper phrasing.找不到答案或正确的措辞。
I want to pass a value to the function that will be sent into my component.我想将一个值传递给将被发送到我的组件中的函数。 For example, I want to do the same as what an event handler does.例如,我想做与事件处理程序相同的事情。 Except that I want to be passing the value (ie the event obj or in my case and id).除了我想传递值(即事件 obj 或在我的情况下和 id)。
const Foo = ({ onSort }) => {
return <Bar onSort={ onSort } />;
Lets say the contract for onSort
is (a: Array<T>, b: Array<T>, id?: string)
.假设onSort
的契约是(a: Array<T>, b: Array<T>, id?: string)
。 I am not sure that this how the function contract should be but I want to be the one passing the id
into the onSort
that is given as prop to Bar
.我不确定函数契约应该如何,但我想成为将id
传递到作为道具给Bar
的onSort
那个。 Hope that makes sense.希望这是有道理的。
Do I just wrap it and send it in?我只是把它包起来寄过去吗? But that would just call it no?但这只是说不?
If I understand you well, you want to send a function to a child component, right?如果我理解你的话,你想向子组件发送一个函数,对吗? As I can see you are using Typescript, so you will need to create the interface of the component props
to create its signature.正如我所看到的,您正在使用 Typescript,因此您需要创建组件props
的接口来创建其签名。
interface BarProps {
onSort: (id: string) => void
}
class Bar extends React.Component<BarProps> {}
Then, to use your component you will need to provide to Bar
a function to onSort
that respects the interface.然后,要使用您的组件,您需要向Bar
提供一个符合界面的onSort
函数。
const Foo = ({ onSort }: {onSort: (param: string) => void}) => {
return <Bar onSort={(id: string) => onSort(id) } />;
}
If Foo
's onSort
property has the same signature as Bar
's onSort
, then you can pass it directly.如果Foo
的onSort
酒店有相同的签名Bar
的onSort
,那么你可以直接通过。
Ps: The id
parameter value, in this case, must always come from Bar
component. Ps: id
参数值,在这种情况下,必须始终来自Bar
组件。
We can use bind or arrow function to pass value to function prop as described here: https://stackoverflow.com/a/39226976/7245915我们可以使用绑定或箭头函数将值传递给函数 prop,如下所述: https : //stackoverflow.com/a/39226976/7245915
But a good way to pass value to a function prop is: https://stackoverflow.com/a/49337689/7245915但是将值传递给函数 prop 的一个好方法是: https : //stackoverflow.com/a/49337689/7245915
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.