我试图在点击服务列表中的特定服务时添加带图像的div,我对React很新,有人可以指导我完成这个,我将不胜感激。
var ServiceChooser = React.createClass({
getInitialState: function () {
return { total: 0 };
},
addTotal: function (price) {
this.setState({ total: this.state.total + price });
},
render: function () {
var self = this;
var services = this.props.items.map(function (s) {
// Create a new Service component for each item in the items array.
// Notice that I pass the self.addTotal function to the component.
return <Service name={s.name} price={s.price} active={s.active} addTotal={self.addTotal}/>;
});
return <div>
<h1>Our services</h1>
<div id="services">
{services}
<p id="total">Total <b>${this.state.total.toFixed(2)}</b></p>
</div>
</div>;
}
});
var Service = React.createClass({
getInitialState: function () {
return {
active: false,
showdetails: false
};
},
clickHandler: function () {
var active = !this.state.active;
this.setState({ active: active });
// Notify the ServiceChooser, by calling its addTotal method
this.props.addTotal(active ? this.props.price : -this.props.price);
//showdetails = true;
// console.log(this.props.name);
return <Details name={this.props.name} price={this.props.price} showdetails={true}/>;
},
render: function () {
return <p className={this.state.active ? 'active' : ''} onClick={this.clickHandler}>
{this.props.name} <b>${this.props.price.toFixed(2)}</b>
</p>;
}
});
var services = [
{ name: 'Web Development', price: 300 },
{ name: 'Design', price: 400 },
{ name: 'Integration', price: 250 },
{ name: 'Training', price: 220 }
];
// Render the ServiceChooser component, and pass the array of services
React.render(
<ServiceChooser items={services} />,
document.getElementById('content')
);
答案 0 :(得分:0)
您需要将this
绑定到组件方法。这可以通过这种方式完成(例如):
return <Service name={s.name} price={s.price} active={s.active} addTotal={self.addTotal.bind(this)} />;
此外,我不太确定是否
this.props.addTotal(active ? this.props.price : -this.props.price);
由于带有前缀-
,会抛出错误。我更喜欢this.props.price * -1
而不是。{/ p>