/** @jsx React.DOM */ var Car = function (wheel, brand) { this.wheel = wheel; this.brand = brand; }; Car.prototype.run = function () { console.log('go!');
var Bike = function (wheel) { this.wheel = wheel; } var car = new Car(4, 'Toyota'); var bike = new Bike(2); console.log(car var Test = React.createClass({ propTypes: { vihicle: React.PropTypes.instanceOf(Car) }, render: function () { return ( <p>I drive {this.props.vihicle.brand} car and its has {this.props.vihicle.wheel} </p> ); } }); React.renderComponent(<Testvihicle={car} />, document.getElementById('car')); // React.renderComponent(<Test vihicle={bike} />, document.getElementById('bike'));
/** @jsx React.DOM */ var ComponentWithDefault = React.createClass({ getDefaultProps: function () { return {value: 'B'} }, render: function () { return ( <div>{this.props.value}</div> ); } }); React.renderComponent(<ComponentWithDefaultvalue='A' />, document.getElementById('example'));
getDefaultProps 將會把預設值暫存起來,以確保 this.props.value 有值。以上面的實際範例來說如果你不帶值則值會是 B ,如果有值則預設值會被取代。這使得你可以放心使用 props ,而無需反覆撰寫脆弱的代碼來處理元件。
傳遞 Props 的捷徑
常見的 React 元件是用基本 HTML 組合的延伸。通常你會想要傳遞屬性給 HTML 元素,React 提供了 transferPropsTo() 方法可以把屬性帶入讓你少打一些字。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/** @jsx React.DOM */
var CheckLink = React.createClass({ render: function() { // transferPropsTo() will take any props passed to CheckLink // and copy them to <a> returnthis.transferPropsTo(<a>{'√ '}{this.props.children}</a>); } });
var CheckLink = React.createClass({ render: function() { // transferPropsTo() will take any props passed to CheckLink // and copy them to <a> return (<ahref={this.props.href}>{'√ '}{this.props.children}</a>); } });