簡體   English   中英

將功能組件轉換為基於類的組件

[英]Converting functional component to class based component

我需要將功能組件轉換為基於類的組件。 我對React還是很陌生,但是我嘗試了轉換組件。 我收到錯誤-ReferenceError:無法找到變量:Props

我的問題是,應在哪里添加基於類的組件中存在的道具以使轉換起作用?

基於類的組件是模態,具有從父組件觸發的形式,因此效果很好。 表單使用的狀態變量在基於類的組件中不起作用,因此我需要將當前的功能組件轉換為基於類的組件。 我正在使用React的16.6.3版本,因為其他軟件包無法在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:無法找到變量:Props

在基於類的組件中, props在類的主要范圍內公開。 您應該使用this關鍵字閱讀

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

我假設您要使用State作為遷移到Class組件的原因。 相反,我建議使用React Hooks,這是最新且優雅的方法。

const ShowModal = props => (

const [state, setState] = React.useState({});

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

反應鈎子: https : //medium.com/frontmen/react-hooks-why-and-how-e4d2a5f0347

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM