本文为小伙伴们介绍的是关于html页面中使用react的场景解析,感兴趣的小伙伴一起来看看吧。
该方案使用场景:在html页面中使用react,主js文件index.js和其它非react功能使用js模块化的方式开发,适合轻量级中小型应用
index.html代码:
引入react、react-dom、babel、moment、antd等
React in HTML css">
index.js代码:
import { ReactComponentContainer } from './ReactComponentContainer.js' let isShow = true; let helloReactContainer; $('#btn').on('click', function () { if (isShow) { helloReactContainer = new ReactComponentContainer('helloReact', HelloReact, { name: 'React' }); helloReactContainer.show(); isShow = false; $(this).val('隐藏React组件'); } else { helloReactContainer.hide(); isShow = true; $(this).val('显示React组件'); } });
ReactComponentContainer.js代码:
该模块用于在html中显示隐藏react组件
class ReactComponentContainer { component componentProps componentContainerId constructor(componentContainerId, component, componentProps) { if ($('#' + componentContainerId).length == 0) { $('body').append(''); } this.componentContainerId = componentContainerId; this.component = component; this.componentProps = componentProps; } render(isShow) { ReactDOM.render( React.createElement( antd.ConfigProvider, { locale: antd.locales.zh_CN }, React.createElement(this.component, Object.assign({ isShow: isShow }, this.componentProps)) ), document.getElementById(this.componentContainerId) ); } show() { this.render(true); } hide() { this.render(false); } } export { ReactComponentContainer }
HelloReact.jsx代码:
class HelloReact extends React.Component { dateFormat = 'YYYY-MM-DD' timeFormat = 'HH:mm:ss' constructor(props) { super(props); let now = new Date().valueOf(); this.state = { dateStr: moment(now).format(this.dateFormat), timeStr: moment(now).format(this.timeFormat) } this.onChangeDate = this.onChangeDate.bind(this); this.onChangeTime = this.onChangeTime.bind(this); this.updateDatePickerAndTimePicker = this.updateDatePickerAndTimePicker.bind(this); } onChangeDate(date, dateString) { this.setState({ dateStr: dateString }); } onChangeTime(time, timeString) { this.setState({ timeStr: timeString }); } updateDatePickerAndTimePicker() { let now = new Date().valueOf(); this.setState({ dateStr: moment(now).format(this.dateFormat), timeStr: moment(now).format(this.timeFormat) }); } render() { return; } }Hello {this.props.name}, Now is {this.state.dateStr} {this.state.timeStr}
更新日期时间控件值
效果图:
浏览器按F12弹出DevTools,在Sources选项卡中可以看到组件代码,方便打断点调试
遇到的问题:
无法使用es6的import语法导入react组件,es6的import和require.js都不认识jsx
react组件不是按需加载,只适合小型应用
以上就是关于html页面中使用react的场景解析的全部内容了,感兴趣的小伙伴记得点击关注哦。