javascript - 将功能组件转换为基于类的组件

标签 javascript reactjs react-native

我需要将功能组件转换为基于类的组件。我对 React 相当陌生,但我尝试过转换该组件。我收到错误 - ReferenceError:找不到变量:Props

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

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

功能组件

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:找不到变量:Props

最佳答案

在基于类的组件中,props 在类的主作用域中公开。您应该使用 this 关键字来阅读它

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

关于javascript - 将功能组件转换为基于类的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57691910/

相关文章:

reactjs - react 和 Redux : Proper Way To Store Loading State in Redux

javascript - 递减计数器有奇怪的行为

javascript - jquery 检查所有输入 :checkbox on button click

javascript - 在 React Native 中创建一个简单的标签格式化程序

javascript - Jquery 在点击时更改 CSS 类

javascript - ReactJS , setState 问题 onChange 事件

javascript - react ,不兼容的覆盖,应该有签名

react-native - 当元素加载到当前位置上方时,如何在可 ScrollView 中保持位置?

php - 用php解析javascript文件

javascript - JQuery 切换数字和字符输入