在Vue.js中,我们可以像这样发出带有参数的自定义事件:
this.$emit('bark', 3);
然后我们可以在父组件上监听此事件,如下:
<parent-component @bark=handleBark />
handleBark (howManyTimes) {
console.log(howManyTimes);
// logs 3
}
我们如何在React中实现这一点?
在Vue.js中,我们可以像这样发出带有参数的自定义事件:
this.$emit('bark', 3);
然后我们可以在父组件上监听此事件,如下:
<parent-component @bark=handleBark />
handleBark (howManyTimes) {
console.log(howManyTimes);
// logs 3
}
我们如何在React中实现这一点?
正如@usafder所提到的那样。我只是为输入字段添加了基本的回调函数。所以在控制台上,您可以看到当前值。
基本上回调函数是从子组件获取数据的一种方式。
Parent.js
import React from "react";
import Child from "./Child";
export default function App() {
const parentHandleChange = (e) => {
console.log(e.target.value);
};
return (
<div>
<Child handleChange={parentHandleChange} />
</div>
);
}
Child.js
import React from "react";
const Child = (props) => {
return <input onChange={props.handleChange} />;
};
export default Child;
使用 codesandbox 进行工作。
如果需要返回自定义值,请按照以下方式使用。
<Child onHandleChange={() => parentHandleChange(10)}
因为这样它不会在每次调用时传递值。
你只需要将自定义事件处理程序作为 props
传递即可。
例如,如果你有一个Parent
和 Child
函数组件。然后你可以在Parent
组件中定义自定义事件处理程序:
function Parent(props) {
const handleBark = (howManyTimes) => {
console.log(howManyTimes);
};
// note below I am sending the handleBark method to Child as props
return (<Child bark={handleBark} />);
}
然后在Child
组件内,您只需将它称为:
props.bark(10);
createEventDispatcher()
和 Vue 的 $emit
。evento
),然后像使用 $emit 一样通过传递事件名称和负载来使用调度程序:const Dog = (props) => {
const evento = useCreateEvento(props)
return <button onCLick={() => evento('bark', 3)}>wof</button>
}
on
+组件事件的大写名称。数据将存储在event.detail
中。<Dog onBark={e => console.log(`barked ${e.detail} times`)} />
/* will log 'barked 3 times'*/
bark
例子呢? - Pooria Han