我想使用React(使用webpack构建)为网站构建组件。我不想做一个复杂的安装工作。到现有网站。只需添加脚本即可“#”;
我无法弄清楚如何创建组件/类并使用参数添加它。 此代码将初始化页面上的组件,但忽略messageText和initialCount。我也试过没有'数据 - '
的index.html
<div id="Docker" data-messageText="Test user" data-initialCount="2"/>
<script src="assets/js/docker.js"></script>
docker.jsx
var React = require('react');
var Docker = React.createClass({
getInitialState: function() {
return {
count: parseInt(this.props.initialCount),
label: this.props.messageText
};
},
handleClick: function () {
this.setState({count: parseInt(this.state.count) + 1});
},
render: function() {
return (
<div>
<div>Hello from: {this.state.label}</div>
<div onClick={this.handleClick}>{this.state.count}</div>
</div>
);
}
});
React.render(
<Docker />,
document.getElementById('Docker')
);
希望在任何网页中添加组件:
<Docker messageText="Test user" initialCount="2"/>
<script src="assets/js/docker.js"></script>
答案 0 :(得分:1)
您必须从div获取值并将它们传递给Docker组件,如此
var Docker = React.createClass({
getInitialState: function() {
return {
count: parseInt(this.props.initialCount),
label: this.props.messageText
};
},
handleClick: function () {
this.setState({count: parseInt(this.state.count) + 1});
},
render: function() {
return (
<div data-messageBox={this.state.label} data-initialCount={this.state.count}>
<div>Hello from: {this.state.label}</div>
<div onClick={this.handleClick}>{this.state.count}</div>
</div>
);
}
});
var docker = document.getElementById('Docker');
var messageText = docker.dataset.messagetext;
var initialCount = docker.dataset.initialcount;
ReactDOM.render(
<Docker messageText={messageText} initialCount={initialCount}/>,
document.getElementById('Docker')
);