繁体   English   中英

react-native:我可以在方法中使用道具吗?

[英]react-native : Can I use props in a method?

我有我的 class 并且我有一个方法,我想知道我是否可以在方法中使用props

请注意,我尝试在methodTwo中使用道具。 这可能吗? 如果没有,有没有办法可以props in method

import React from 'react';
import { Image, Text, View } from 'react-native';

export default class Test extends React.PureComponent {

  methodOne = () => {
    this.setState({
      one:false,
      two:false,
      three:false
    })
  }

  methodTwo = () => {
    this.setState({
      one:false,
      two:false,
//I want to use props
      three:this.props.three
    })
  }

  render() {

    return (
      <View style={{   backgroundColor: 'transparent', alignItems: 'center' }}>
        <Button title='one' onPress={()=>this.methodOne()}/>

// I could call i like this?
        <Test three='newState'/>
      </View>
    );
  }
}
  methodTwo = () => {
    this.setState({
      one:false,
      two:false,
      three:this.props.three
    })
  }

props-> 是从父组件传递到子组件的值。 在基于 class 的组件中,您可以使用this.props.Attribute_name获取值,在基于功能的组件中,您可以使用props.Attribute_name获取值(记住基于功能的组件对此没有任何概念)

如果你想使用 this.props.three,那么在父组件调用中(调用这个特定组件的组件) <Test three="anyValue" />那么你可以很容易地在子组件中获取这个值。

 class Cat extends React.Component { render() { const mouse = this.props.mouse; return ( <img src="/cat.jpg" style={{ position: 'absolute', left: mouse.x, top: mouse.y }} /> ); } } class MouseWithCat extends React.Component { constructor(props) { super(props); this.handleMouseMove = this.handleMouseMove.bind(this); this.state = { x: 0, y: 0 }; } handleMouseMove(event) { this.setState({ x: event.clientX, y: event.clientY }); } render() { return ( <div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}> {/* We could just swap out the <p> for a <Cat> here... but then we would need to create a separate <MouseWithSomethingElse> component every time we need to use it, so <MouseWithCat> isn't really reusable yet. */} <Cat mouse={this.state} /> </div> ); } } class MouseTracker extends React.Component { render() { return ( <div> <h1>Move the mouse around;</h1> <MouseWithCat /> </div> ); } }

如果您从父组件传递了this.props.xxxx语法,则整个 class scope 都可以访问这些道具。 所以你也可以在 methodOne 中使用。

您可以在方法中使用道具。 您面临的任何具体错误?

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM