如何在当前组件中调用其他组件功能?它们也都在不同的脚本中。
任何人都知道如何以原生的方式做到这一点?
//ClassOne.js
class ClassOne extends React.Component {
constructor(props) {
super(props);
}
setValue(){
}
}
//ClassTwo.js
class ClassTwo extends React.Component {
constructor(props) {
super(props);
}
callSetValue(){
ClassOne.setValue(); HOW???
}
}
答案 0 :(得分:0)
您可以将ClassOne.setValue作为属性传递给ClassTwo。
//ClassOne.js
class ClassOne extends React.Component {
constructor(props) {
super(props);
}
setValue(){
// Do stuff
}
}
//ClassTwo.js
class ClassTwo extends React.Component {
constructor(props) {
super(props);
}
callSetValue(){
if (this.props.onSetValue) this.props.onSetValue(); // this can be set to any function, including ClassOne's setValue
}
}
答案 1 :(得分:0)
除非您要调用的函数是静态的,否则必须在要调用函数的范围内实例化所需的任何类。比如ClassTwo,你想在ClassOne中调用一个方法...在ClassTwo中实例化一个ClassOne实例,然后使用该对象调用该函数。
答案 2 :(得分:0)
很明显,不是在ReactJS中的推荐方式,甚至是React-Native。也许您想遵循面向对象的编程规则,但在这里我们可以在ReactJS中进行全功能开发。对于这种情况,我更喜欢使用一个辅助函数,在这两个类中,我都导入并使用该辅助函数:
// set value helper function
export const setValueHelper = () => {
// do something
};
然后在课程中:
import { setValueHelper } from 'helpers';
//ClassOne.js
class ClassOne extends React.Component {
constructor(props) {
super(props);
}
setValue(){
setValueHelper();
}
}
import { setValueHelper } from 'helpers';
//ClassTwo.js
class ClassTwo extends React.Component {
constructor(props) {
super(props);
}
setValue(){
setValueHelper();
}
}