3 回答
TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊
OP使這個(gè)問(wèn)題成為一個(gè)移動(dòng)的目標(biāo)。它又被更新了。因此,我覺(jué)得有責(zé)任更新我的答復(fù)。
首先,回答您提供的示例:
onClickthis.props.onClick.bind(null, this):
var Child = React.createClass({
render: function () {
return <a onClick={this.props.onClick.bind(null, this)}>Click me</a>;
}}); onClick: function (component, event) {
// console.log(component, event);
},但這個(gè)問(wèn)題本身就有誤導(dǎo)性。
props.
var Child = React.createClass({
render: function () {
return <a onClick={this.props.onClick}> {this.props.text} </a>;
}});var Parent = React.createClass({
getInitialState: function () {
return { text: "Click here" };
},
onClick: function (event) {
// event.component.props ?why is this not available?
},
render: function() {
return <Child onClick={this.onClick} text={this.state.text} />;
}});在這個(gè)例子中,你已經(jīng)清楚地知道了什么是孩子的道具。
如果它真的是關(guān)于使用孩子的道具…
props
var Child = React.createClass({
render: function () {
return <a {...this.props}> {this.props.text} </a>;
}});var Parent = React.createClass({
getInitialState: function () {
return { text: "Click here" };
},
onClick: function (text) {
alert(text);
},
render: function() {
return <Child onClick={this.onClick.bind(null, this.state.text)} text={this.state.text} />;
}});
當(dāng)您連接其他的子組件時(shí),不需要額外的配置
var Parent = React.createClass({
getInitialState: function () {
return {
text: "Click here",
text2: "No, Click here",
};
},
onClick: function (text) {
alert(text);
},
render: function() {
return <div>
<Child onClick={this.onClick.bind(null, this.state.text)} text={this.state.text} />
<Child onClick={this.onClick.bind(null, this.state.text2)} text={this.state.text2} />
</div>;
}});一個(gè)健壯的實(shí)例
孩子們完全無(wú)知。
ServiceItem
<div onClick={this.props.handleClick.bind(this.props.index)} />
handleClickindex[
父母是孩子
DTServicesCalculator
DTServiceCalculatorServiceItemServiceItem
<ServiceItem chosen={chosen} index={i} key={id} price={price} name={name} onSelect={this.props.handleServiceItem} />
handleServiceItem
handleServiceClick (index) {
this.props.onSelect(index);}所有人都知道
handleSelect (index) {
let services = […this.state.services];
services[index].chosen = (services[index].chosen) ? false : true;
this.setState({ services: services });}結(jié)語(yǔ)
TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
var Child = React.createClass({
render: function() {
<a onClick={this.props.onClick.bind(null, this)}>Click me</a>
}});var Parent = React.createClass({
onClick: function(component, event) {
component.props // #=> {Object...}
},
render: function() {
<Child onClick={this.onClick} />
}});bind(null, this)this.props.onClickcomponentevent
添加回答
舉報(bào)
