我有以下代码可以正常工作。当我在底部注释掉反应脚本并将其添加到clickme.js文件时,我得到了意外的令牌<在渲染函数返回的第一个div上。
<!DOCTYPE html>
<html>
<head>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.0/react.min.js"></script>
<script crossorigin src="https://cdn.jsdelivr.net/npm/create-react-class@15.6.2/create-react-class.js"></script>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.4.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='clickme.js'></script>
<title>Click Me</title>
</head>
<body>
<div>
Count:<span id="cnt1">0</span>
<button id='btn1' type='button' style="width:60px">JS only</button>
</div>
<br>
<div>
Count:<span id="cnt2">0</span>
<button id='btn2' type='button' style="width:60px">Jquery</button>
</div>
<br>
<div id='react-example'> </div>
<script type='text/jsx'>
var btnCSS = {
width: '60px',
textAlign:'center',
padding:0,
border:0
};
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0};
}
incrementCount() {
this.setState( {count: this.state.count + 1});
}
render() {
return (
<div> Count:{this.state.count}
<button type="button" style={btnCSS}
onClick={ this.incrementCount.bind(this) }>React</button>
</div>
);
}
};
ReactDOM.render(
<Counter />,
document.getElementById('react-example')
)
</script>
</body>
</html>
这是clickme.js文件:
document.addEventListener("DOMContentLoaded", function(event) {
var counter = Number(document.getElementById("cnt1").innerHTML);
document.getElementById("btn1").addEventListener("click", function(){
counter = counter + 1;
document.getElementById("cnt1").innerHTML=counter;
});
});
$(document).ready(function(){
var counter= Number($("#cnt2").html());
$("#btn2").click(function() {
counter = counter + 1;
$("#cnt2").html(counter);
});
});
document.addEventListener("DOMContentLoaded", function(event) {
var btnCSS = {
width: '60px',
textAlign:'center',
padding:0,
border:0
};
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0};
}
incrementCount() {
this.setState( {count: this.state.count + 1});
}
render() {
return (
<div> Count:{this.state.count}
<button type="button" style={btnCSS}
onClick={ this.incrementCount.bind(this) }>React</button>
</div>
);
} };
ReactDOM.render(
<Counter />,
document.getElementById('react-example')
)
});
答案 0 :(得分:3)
只需将type="text/jsx"
添加到外部脚本标记:
<script src="clickme.js" type="text/jsx"></script>