简体   繁体   English

如何将 function 和组件 class 中的数据传递给 React Native 中的无状态 class?

[英]How to pass function and data from component class to stateless class in React Native?

I am working with react native and I want to pass function and some data from Component class to another Stateless class, but I could not make to passing function and data part. I am working with react native and I want to pass function and some data from Component class to another Stateless class, but I could not make to passing function and data part.

Here you can see my Component class:在这里你可以看到我的组件 class:

class Classroom extends Component {

    constructor(props, context) {
        super(props, context);



    };

    state = {
        isLightOn: false,
        title : "Turn light on "
    }

   onPress() {
       this.setState({isLightOn: !this.state.isLightOn})
       console.log(this.state.isLightOn)
       this.setState({title:this.state.isLightOn===false ?"Turn light off":"Turn light on"})

   }

    render() {
        return (
            <View style={styles.blue}>

                <LightBulb  isLightOn={this.state.isLightOn}> </LightBulb>
                <LightButton onPress={this.onPress} isLightOn={this.state.isLightOn} title={this.state.title} > </LightButton>


            </View>
        );
    }


}

Firstly, I want to pass isLightOn and title datas to my LightButton class (which mean to my stateless class).首先,我想将isLightOn标题数据传递给我的LightButton class(这意味着我的无状态类)。 After that, I want to use onPress function inside of my Stateless class, but I cannot use.之后,我想在我的无状态 class 内部使用 onPress function,但我不能使用。 I am taking that error:我正在接受这个错误:

Maximum update depth exceeded.超过最大更新深度。 This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React limits the number of nested updates to prevent infinite loops. React 限制了嵌套更新的数量以防止无限循环。

I also LightButton onPress={this.onPress} remove parenthesis, but still taking error.我也 LightButton onPress={this.onPress} 删除括号,但仍然出错。

Here is my my Stateless class这是我的无状态 class

const LightButton = ({onPress,isLightOn,title}) => (


        <View style={styles.red}>


            <Button
                title= {title}
                onPress={() => {}

                }
            />
        </View>
)

I want to use onPress function and datas inside of the this class.我想使用 onPress function 和这个 class 里面的数据。 As a result, How can I pass function and data to that class?结果,如何将 function 和数据传递给 class?

The main issue here is that you need to declare onPress using an arrow function or bind it to the component's this value within the constructor.这里的主要问题是您需要使用箭头 function 声明onPress或将其绑定到构造函数中组件的this值。 Otherwise it wouldn't have access to the correct this value.否则它将无法访问正确的 this 值。 Other than that, the way you were passing props into components is perfectly fine.除此之外,您将道具传递给组件的方式非常好。

I also merged your two set state calls in onPress to one as it's easier.我还将onPress中的两组 state 调用合并为一个,因为它更容易。

In LightButton, I set it up like this to pass the onPress function down to the button:在 LightButton 中,我将其设置为将 onPress function 向下传递给按钮:

const LightButton = ({ onPress, isLightOn, title }) => (
  <div style={{backgroundColor:'red'}}>
    <Button title={title} onPress={onPress} />
  </div>
);

(I set it up using react, but the issues at hand are more of a JS issue than a React/ReactNative one, so the advice should still be valid:) ) (我使用 react 设置它,但手头的问题更多的是 JS 问题而不是 React/ReactNative 问题,所以建议应该仍然有效:))

 const { Component } = React; const View = 'div'; const Button = (({title,onPress})=><button onClick={onPress}>{title}</button>); const LightBulb = ({ isLightOn }) => { return <div className={'LightBulb' + (isLightOn? ' on': '')} />; }; const LightButton = ({ onPress, isLightOn, title }) => ( <div style={{backgroundColor:'red'}}> <Button title={title} onPress={onPress} /> </div> ); class Classroom extends Component { state = { isLightOn: false, title: 'Turn light on ', }; onPress=()=> { console.log(this.state.isLightOn); this.setState({ title: this.state.isLightOn === false? 'Turn light off': 'Turn light on', isLightOn: .this.state;isLightOn }): } render() { return ( <div style={{backgroundColor.'blue'}}> <LightBulb isLightOn={this.state.isLightOn}> </LightBulb> <LightButton onPress={this.onPress} isLightOn={this.state.isLightOn} title={this.state;title} >Button</LightButton> </div> ). } } ReactDOM,render(<Classroom />. document;querySelector('#root'));
 .LightBulb { height: 50px; width: 50px; border-radius: 50px; background-color: black; }.LightBulb.on { background-color: white; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"/>

You can assign it like你可以像这样分配它


const LightButton = ({onPress,isLightOn,title}) => (
  ...
  onPress={onPress}
  ...

or with an arrow function if you need to pass arg inside或使用箭头 function 如果您需要在内部传递 arg


onPress={()=>onPress(someArg)}

do notice that you either don't put () at all, or twice () => func() for not run the function while it is just loads and not clicked.请注意,您要么根本不放() ,要么两次() => func()不运行 function,而它只是加载而不是单击。

unrelated directly to your issue but something that you encounter is inside onPress by doing like so与您的问题直接无关,但您遇到的事情在onPress内部,这样做


 this.setState({isLightOn: !this.state.isLightOn})
 console.log(this.state.isLightOn)
 this.setState({title:this.state.isLightOn===false ?"Turn light off":"Turn light on"})

setState it is an async call, and therefore second setState usage not guaranteed to refer the state as you expect, use setState({... }, () => callback()) or all at one line and accords to prev state setState它是一个异步调用,因此第二个setState用法不能保证按照您的预期引用 state,使用setState({... }, () => callback())或全部在一行中并符合 prev state


 this.setState({isLightOn: !this.state.isLightOn, title: !this.state.isLightOn===false ?"Turn light off":"Turn light on"})
  1. First thing you did wrong is your state instantiating !您做错的第一件事是您的 state 实例化! you need to instantiate your state in the constructor block like:您需要在constructor块中实例化您的 state,例如:
constructor(props, context) {
  super(props, context);
  this.state = { counter: 0 };
}
  1. onPress() you use this for your function which is not recommended in react native or any other language, those are dedicated functions and methods of React Native onPress()你将它用于你的 function 不建议在 react native 或任何其他语言中使用,这些是 React Native 的专用功能和方法

  2. For passing a parameter or calling a function it is better to use these patterns ====>对于传递参数或调用 function 最好使用这些模式 ====>

onPress={() => urFunction()} with parenthesis or onPress={() => urFunction()}带括号或

onPress={urFunction} without parenthesis onPress={urFunction}不带括号

Do the modifications I hope it helps <3做修改我希望它有帮助<3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在本机反应中将无状态 function 转换为 class 组件 - How can I convert stateless function to class component in react native 如何将 Class 组件转换为 Function 无状态组件? - How to transform a Class Component to a Function Stateless Component? 如何从无状态父级访问子 class 组件中的 function? - How to access a function in a child class component from a stateless parent? 如何将功能从有状态组件传递到无状态组件? - How to pass function from statefull to stateless component? 如何将数据从类传递到 React Native 数组、firebase、堆栈导航器 v5 中的函数 - How to pass data from Class to function in React Native array, firebase, stack navigator v5 如何将数据从 class React.Component 传递到 jsx 文件 - How to pass data from class React.Component to jsx file 将React类组件转换为React无状态组件 - Converting react class component to react stateless component 如何将 react-native 道具从功能组件传递到 class 组件 - How to pass react-native props from functional component to class component 将无状态功能组件反应为类组件 - React stateless functional component to class Component 无法从读取到 Function 组件的 React Native 异步文件中获取数据(但在 Class 组件中有效) - Cannot get data from React Native asynchronous file reading into Function Component (but works in Class Component)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM