过滤react.js

时间:2016-05-01 07:22:33

标签: javascript reactjs react-native

说我有一个记录列表,我想根据用户选择的选择框过滤它们。我在jsfiddle中有详细信息。

http://jsfiddle.net/reactjs/69z2wepo/

因此,如果用户选择1-10,则只显示1到10中的那些数字。 我们如何添加事件处理程序来过滤所有记录?

var numbers =   [   
    {"number":1},    {"number":2},    {"number":3},    {"number":4},    {"number":5},    {"number":6},    {"number":7},    {"number":1},    {"number":1},    {"number":1},    {"number":1},    {"number":1},    {"number":1},    {"number":18},    {"number":11},    {"number":1},    {"number":1},    {"number":1},    {"number":1},    {"number":1},    {"number":21},    {"number":41},    {"number":1},    {"number":1},    {"number":1},    {"number":1},    {"number":1},     {"number":14},    {"number":1},    {"number":1},    {"number":1},    {"number":1},    {"number":1},    {"number":81},    {"number":12},    {"number":1},    {"number":1},    {"number":1},    {"number":1},    {"number":1},    {"number":1},    {"number":111}
];
var DisplayNumbers = React.createClass({    
render: function(){

return (
<div>
    {this.props.allnumbers}
  </div>
);
}
       });
 var FilterBox = React.createClass({
      getInitialState: function() {
        return { selected: "1-10" }
      },      

            render: function() {
        return (
          React.createElement("select", { value: this.state.selected },
             React.createElement("option", { value: 1 }, "1-10"),
             React.createElement("option", { value: 2 }, "11-20"),
             React.createElement("option", { value: 3 }, "21-30"), 
          React.createElement("option", { value: 4 }, "31-40")
          )
        )
      }
    });


var App = React.createClass({
    render: function() {              
        return (
        <div>
          <FilterBox />
                      <h1>Requests</h1>
                <DisplayNumbers allnumbers={this.props.data} />
          </div>
        );
    }
});
ReactDOM.render(<App data={numbers}/>, document.getElementById('container'));

2 个答案:

答案 0 :(得分:2)

由于@Scarysize建议您必须向表单元素提供onChange个事件处理程序。此外,在DisplayNumbers组件中,您正在尝试渲染js对象的数组,但是反应将不会呈现它。它必须是一系列合法反应组件才能以这种方式呈现。

在这个小提琴中:https://jsfiddle.net/sehrob/r4c2ycmc/ - 我对您的代码进行了一些更改以使其可行。如果你愿意,你可以使用它。

P.S。 Thinking in React对您实施应用也非常有用。

答案 1 :(得分:1)

只需将onChange处理程序附加到select元素即可。处理程序应更新组件状态,这将导致重新呈现。在渲染功能中,您可以根据新状态确定要显示的元素。

另请查看可能对您有帮助的数组函数mapfilterhttps://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map