首页 > 解决方案 > 将功能组件转换为基于类的组件

问题描述

我需要将功能组件转换为基于类的组件。我对 React 还很陌生,但我尝试过转换组件。我收到错误 - ReferenceError: Cant find variable: Props

我的问题是,我在哪里添加基于类的组件中存在的道具以使转换工作?

基于类的组件是一个模式,其表单从父组件触发,效果很好。该表单使用在基于类的组件中不起作用的状态变量,因此我需要将当前的功能组件转换为基于类的组件。我使用的是 16.6.3 版的 React,因为其他软件包不适用于较新版本的 React-Native,所以我不能在这个版本中使用钩子。

功能组件

const ShowModal = props => (
  <Modal
    visible={props.display}
    animationType="slide"
    onRequestClose={() => console.log("closed")}
  >
   ...Other stuff in here. 
 </Modal>
);
export default ShowModal;

基于类的组件

export default class ShowModal extends Component {
  state = {     
  };

  render() {
    return (
      ...Other stuff in here 
    );
  }
}

我收到错误 - ReferenceError: Cant find variable: Props

标签: javascriptreactjsreact-native

解决方案


基于类的组件props暴露在类的主要范围内。您应该使用this关键字阅读它

class Component extends React.Component{
    render(){return this.props.value}
}

推荐阅读