Poo*_*Han 37 javascript reactjs
在 Vue.js 中,我们可以发出自定义事件以及参数,例如
this.$emit('bark', 3);
Run Code Online (Sandbox Code Playgroud)
然后我们可以在父组件上监听这个事件,例如
<parent-component @bark=handleBark />
handleBark (howManyTimes) {
console.log(howManyTimes);
// logs 3
}
Run Code Online (Sandbox Code Playgroud)
我们如何在 React 中做到这一点?
DIL*_*MAS 26
正如@usafder 提到的那样。我只是为输入字段添加基本回调函数。所以在控制台上你可以看到当前的值。
基本上回调函数是从子组件获取数据的方法。
父.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>
);
}
Run Code Online (Sandbox Code Playgroud)
Child.js
import React from "react";
const Child = (props) => {
return <input onChange={props.handleChange} />;
};
export default Child;
Run Code Online (Sandbox Code Playgroud)
工作代码沙箱
除此之外,如果您需要返回自定义值,请像这样使用
<Child onHandleChange={() => parentHandleChange(10)}
Run Code Online (Sandbox Code Playgroud)
因为在这里,如果你想传递一个值,它不会每次都调用。
usa*_*der 14
您只需将自定义事件处理程序作为 传递即可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} />);
}
Run Code Online (Sandbox Code Playgroud)
然后在Child
组件内部您可以简单地将其称为:
props.bark(10);
Run Code Online (Sandbox Code Playgroud)
您还可以使用我创建的这个库 Evento来复制 SveltecreateEventDispatcher()
和 Vue 的$emit
。
您必须evento
使用钩子创建事件发射器(按约定命名),并通过传递事件名称和有效负载来使用调度程序,就像使用 $emit 一样:
const Dog = (props) => {
const evento = useCreateEvento(props)
return <button onCLick={() => evento('bark', 3)}>wof</button>
}
Run Code Online (Sandbox Code Playgroud)
父组件将能够像侦听 React 事件一样侦听事件:通过使用on
+ 组件事件的大写名称。数据将存储在event.detail
.
<Dog onBark={e => console.log(`barked ${e.detail} times`)} />
/* will log 'barked 3 times'*/
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
35203 次 |
最近记录: |