組件要實現的功能:
1、定製label和輸入框的placeholder的內容;
2、輸入的內容不符合Regex要求時,輸入框標紅,符合時標綠;
3、點擊清除按鈕後,按鈕消失並清除輸入框內容;
4、對外開放3個方法:擷取、設定、刪除輸入框的內容(trim)。
inputBox.html:
<!DOCTYPE html><html><head><link rel="stylesheet" href="inputBox.css"><script src="build/react.js"></script><script src="build/react-dom.js"></script><script src="build/browser.min.js"></script></head><body><div id="inputBox"></div><script type="text/babel" src="inputBox.jsx"></script></body></html>
inputBox.jsx:
var grades = [{team: "Team1", name: "Alice", grade: 80},{team: "Team1", name: "Bruce", grade: 90},{team: "Team1", name: "Cindy", grade: 50},{team: "Team2", name: "David", grade: 40},{team: "Team2", name: "Emy", grade: 60},{team: "Team2", name: "Fruid", grade: 70}];var FilterBox = React.createClass({getInitialState: function() {return {inputText: "",showPassingOnly: false};},filter: function(inputText, showPassingOnly) {this.setState({inputText: inputText,showPassingOnly: showPassingOnly});},render: function() {return (<div><SearchBox onInput={this.filter} inputText={this.state.inputText} showPassingOnly={this.state.showPassingOnly} /><GradeList grades={this.props.grades} inputText={this.state.inputText} showPassingOnly={this.state.showPassingOnly} /></div> );}});var SearchBox = React.createClass({filter: function() {this.props.onInput(this.refs.input.value,this.refs.checkbox.checked);},render: function() {return (<form><input id="text" type="text" ref="input" placeholder="Sreaching..." onChange={this.filter} value={this.props.inputText}/><br/><input type="checkbox" ref="checkbox" checked={this.props.showPassingOnly} onChange={this.filter}/>Only show passing grades</form>);}});var GradeList = React.createClass({render: function() {var rows = [];var teams = [];this.props.grades.forEach(function(grade, index) {if (grade.name.toLowerCase().indexOf(this.props.inputText) == -1 || this.props.showPassingOnly && grade.grade < 60)return;if (teams.indexOf(grade.team) == -1) {rows.push(<Team team={grade.team} key={"team" + index}></Team>);teams.push(grade.team);}rows.push(<Grade name={grade.name} grade={grade.grade} key={"grade" + index}></Grade>);}.bind(this));if (rows.length == 0) rows.push(<tr key={"noMatches"}><td colSpan="2">No matches!</td></tr>);return (<table><thead><tr><th>Name</th><th>Grade</th></tr></thead><tbody>{rows}</tbody></table>);}});var Team = React.createClass({render: function() {return (<tr><td colSpan="2">{this.props.team}</td></tr>);}});var Grade = React.createClass({render: function() {return (<tr><td>{this.props.name}</td><td>{this.props.grade}</td></tr>);}});ReactDOM.render(<FilterBox grades={grades} />,document.getElementById('filterBox'));