不使用箭头函数将参数传递给 prop 函数

IT技术 reactjs react-native arrow-functions react-props
2021-05-10 22:17:49

我听说将箭头函数作为 prop 传递并不理想,因为它每次都会创建一个新函数,这会导致性能问题。但是,我不完全确定如何完全远离它们,如下例所示:

class Home extends Component {

    onCardPress = (message) =>{
        alert(message)
    }

    render(){
        return(
            <View>
                <Card 
                    onCardPress={this.onCardPress}
                    message="Hello world!"
                />
            </View>
        )
    }
}

class Card extends Component {
    render(){
        const { onCardPress , message } = this.props;
        return(
            <TouchableOpacity
                activeOpacity={0.8}
                onPress={()=>{onCardPress(message)}}
            />
        )
    }
}

我曾尝试将onPressinCard更改为onPress={onCardPress(message)},但我知道这不起作用,因为我正在调用该函数而不是将函数对象传递给onPressof TouchableOpacityTouchableOpacity仍然能够message从父组件传递参数的同时删除箭头函数的“正确”方法或最佳实践是Home什么?

4个回答

你可以这样做:

class Card extends Component {
    pressHandler = () => this.props.onCardPress(this.props.message);

    render() {
        return (
            <TouchableOpacity
                activeOpacity={0.8}
                onPress={this.pressHandler.bind(this)}
            />
        );
    } }

如果你想避免箭头函数,你必须使用bind(). 箭头函数会自动绑定 "this"

  class Home extends Component {

      constructor(props) {
       super(props);
       this.onCardPress = this.onCardPress.bind(this);
      }

      onCardPress (message) {
        alert(message)
      }

      render(){
        return(
            <View>
                <Card 
                    onCardPress={this.onCardPress}
                    message="Hello world!"
                />
            </View>
        )
      }
  }



class Card extends Component {
    render(){
        const { onCardPress , message } = this.props;
        return(
            <TouchableOpacity
                activeOpacity={0.8}
                onPress={onCardPress(message)}
            />
        )
     }
 }

据我了解,问题在于在bind内部调用render或从另一个 lambda 返回处理程序,因为这每次都会创建一个新函数。解决这个问题的传统方法是将您的处理程序函数绑定到其他地方——比如在构造函数中。在您的情况下,这可能如下所示:

constructor(props) {
    ....
    this.onCardPress = this.onCardPress.bind(this);
}

...

<Card 
   onCardPress={this.onCardPress}
   message="Hello world!"
/>

给你替代选项作为箭头功能已经在上面的帖子中回答。

class Card extends Component {
   onClick = () => {
      const { onCardPress, message } = this.props;
      onCardPress(message);
    }
    render(){
        const { onCardPress , message } = this.props;
        return(
            <TouchableOpacity
                activeOpacity={0.8}
                onPress={this.onClick}
            />
        )
    }
}