[英]How do I call/execute a function from another component in react native?
How do I call other component function in my current component in react native?如何在 React Native 中调用当前组件中的其他组件函数? They are both in different script as well.
它们也都使用不同的脚本。
Anyone know how to do this in react native?任何人都知道如何在本机反应中做到这一点?
//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???
}
}
You can pass in ClassOne.setValue as a property to ClassTwo.您可以将 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
}
}
Unless the function you are wanting to call is static you must instantiate whatever class you want inside the scope of where you want to call the function.除非您要调用的函数是静态的,否则您必须在要调用该函数的范围内实例化您想要的任何类。 Say in ClassTwo you want to call a method in ClassOne... Instantiate an instance of ClassOne inside of ClassTwo and then call the function using that object.
假设在 ClassTwo 中您想调用 ClassOne 中的方法...在 ClassTwo 中实例化 ClassOne 的一个实例,然后使用该对象调用该函数。
Obviously, it is not a recommended way in ReactJS, even React-Native.显然,它不是ReactJS 中的推荐方式,即使是 React-Native。 Maybe you wanna follow the object-oriented programming rules but here we have fully functional development in ReactJS.
也许你想遵循面向对象的编程规则,但在这里我们在 ReactJS 中进行了全功能开发。 for such your case I prefer to use a helper function and in both of the classes, I import and use the helper function:
对于这种情况,我更喜欢使用辅助函数,并且在这两个类中,我都导入并使用了辅助函数:
// set value helper function
export const setValueHelper = () => {
// do something
};
Then in the classes:然后在课堂上:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.