admin管理员组文章数量:1410705
How do I call other ponent function in my current ponent in 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???
}
}
How do I call other ponent function in my current ponent in 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???
}
}
Share
asked Sep 29, 2015 at 14:29
phongyewtongphongyewtong
5,31915 gold badges59 silver badges87 bronze badges
0
3 Answers
Reset to default 1You can pass in ClassOne.setValue as a property to 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.
Obviously, it is not a remended way in ReactJS, even React-Native. Maybe you wanna follow the object-oriented programming rules but here we have fully functional development in 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();
}
}
本文标签: javascriptHow do I callexecute a function from another component in react nativeStack Overflow
版权声明:本文标题:javascript - How do I callexecute a function from another component in react native? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745043960a2639247.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论