ReactJS - 将多个函数作为单个道具传递给子组件
ReactJS - Pass multiple functions to child components as a single prop
我将多个 function={this.function}
作为单数道具从父组件传递到其子组件。我没有收到任何错误或问题,但我想知道是否有更好/更清晰的编码方式。
为了说明,这里有一个示例代码(父组件):
import React, { Component } from 'react';
export default class App extends Component {
function1 = () => {
// Does something
};
function2 = () => {
// Does something
};
function3 = () => {
// Does something
};
function4 = () => {
// Does something
};
function5 = () => {
// Does something
};
render() {
return (
<div>
Parent Component
<ChildComponent
function1={this.function1}
function2={this.function2}
function3={this.function3}
function4={this.function4}
function5={this.function5} />
</div>
);
}
}
这真的只是代码变得有点长的问题。我想知道是否有一个简短的方法来传递函数 1 到 5,也许在一行中。
提前致谢!
当然,至少有两个选择:
import React, { Component } from 'react';
export default class App extends Component {
functions = {
function1: () => {
// Does something
},
function2: () => {
// Does something
},
function3: () => {
// Does something
},
function4: () => {
// Does something
},
function5: () => {
// Does something
}
}
render() {
return (
<div>
Parent Component
<ChildComponent functions={this.functions} />
OR
<ChildComponent {...this.functions} />
</div>
);
}
}
我将多个 function={this.function}
作为单数道具从父组件传递到其子组件。我没有收到任何错误或问题,但我想知道是否有更好/更清晰的编码方式。
为了说明,这里有一个示例代码(父组件):
import React, { Component } from 'react';
export default class App extends Component {
function1 = () => {
// Does something
};
function2 = () => {
// Does something
};
function3 = () => {
// Does something
};
function4 = () => {
// Does something
};
function5 = () => {
// Does something
};
render() {
return (
<div>
Parent Component
<ChildComponent
function1={this.function1}
function2={this.function2}
function3={this.function3}
function4={this.function4}
function5={this.function5} />
</div>
);
}
}
这真的只是代码变得有点长的问题。我想知道是否有一个简短的方法来传递函数 1 到 5,也许在一行中。
提前致谢!
当然,至少有两个选择:
import React, { Component } from 'react';
export default class App extends Component {
functions = {
function1: () => {
// Does something
},
function2: () => {
// Does something
},
function3: () => {
// Does something
},
function4: () => {
// Does something
},
function5: () => {
// Does something
}
}
render() {
return (
<div>
Parent Component
<ChildComponent functions={this.functions} />
OR
<ChildComponent {...this.functions} />
</div>
);
}
}