如何在Codepen中从一个Pen导入React组件?
在Codepen中跨Pen导入React组件的解决方案
我来帮你解决这个跨Codepen引用React组件的问题——Codepen的运行环境和本地Node项目不太一样,不能直接用ES模块的export/import语法,得换个方式把组件暴露到全局作用域里。
第一步:修改源Pen,把组件暴露到全局
Codepen默认不是模块环境,直接写export default会报错。你需要把Wheel组件挂载到全局的window对象上,这样其他Pen才能访问到它。修改后的源Pen代码如下:
window.Wheel = class Wheel extends React.Component { constructor(props){ super(props); this.state = { spin : false, value: 0 }; this.spin = this.spin.bind(this); } spin(e){ var val = this.state.value + 720 + (Math.floor(Math.random() * 24) * 15); console.log((this.state.value % 360) / 15); e.target.style.webkitTransform = 'rotate(' + -val + 'deg)'; e.target.style.webkitTransition = '-webkit-transform 4s ease-out'; this.setState({value: val}); } render(){ const wheelVals = [800, "BANKRUPT", 200, 300, 350, 250, 400, 300, 200, 250, 500, 350, 250, "BANKRUPT", 200, 300, 400, 250, 600, "LOSE A TURN", 200, 300, 250, 200]; return (<div><img width="400" height="400" src="https://orig00.deviantart.net/0a38/f/2010/242/f/6/singapore_wheel_of_fortune_by_wheelgenius-d2xmb9v.jpg" onClick={(e) => this.spin(e)}/><br/><br/>{wheelVals[(this.state.value % 360) / 15]} </div>); } }
第二步:在目标Pen中直接使用全局组件
你已经在目标Pen的JavaScript引用里添加了源Pen的地址,现在可以直接在代码中使用Wheel组件了(因为它已经存在于全局作用域)。比如在你的MyComponent的render方法中加入这个组件,修改后的目标Pen关键部分代码如下:
// 不需要额外import,直接使用全局的Wheel组件 class MyComponent extends React.Component { // ... 你的其他原有代码保持不变 ... render() { return ( <Grid> {/* 新增:在这里引入Wheel组件 */} <Row className="show-grid" style={{marginBottom: '2vh'}}> <Wheel /> </Row> {/* 原有的其他代码 */} <Row className="show-grid" > { this.state.phrase.split(' ').map((item, j) => ( <div style = {{display:'inline-block'}}> <Letter letter = {' '}/> {item.split('').map((item, i) => ( <Letter letter= {item}/> )) } </div> )) } </Row> {/* ... 剩下的原有代码保持不变 ... */} </Grid> ); } }
为什么本地Node项目可以但Codepen不行?
本地Node项目默认是ES模块环境(或者你配置了模块支持),所以可以用export和import来共享组件。但Codepen默认是把JavaScript代码放在全局作用域中执行,不支持ES模块的导入导出语法,所以必须把组件挂载到window这个全局对象上,让其他Pen能访问到。
内容的提问来源于stack exchange,提问作者ep84
相关产品推荐
相关产品推荐

