Вопрос

how to delete a record onClick(how to identify which item/model is clicked and delete the data from the state). And Do I need a nameRecord created with React.createClass or is it enough to just use a function(does reactjs keep track of each record differently if I use createClass/just function).

var nameRecord = React.createClass({
    handleClick: function(e){
        alert('my name is'+this.props.data.name);
        this.destroy() // can I remove the record
    },
    render: function(){
        return <ol onClick={this.handleClick}>{this.props.data.name}</ol>
    }    
});
var people = [{"name":"king"},{"name":"Larry"}]
var NameList = React.createClass({
  getInitialState: function(){
    return { 
        data: people,
    };
  },
  render:function(){

    people = this.state.data.slice(0,5)
    return <ul>    
        List of Names - 
        {people.map(function(person){
            return <nameRecord data={person}>child</nameRecord>
        })}

      </ul>
      ;
  }

})
React.renderComponent(
  <NameList />,
  document.getElementById('content')
  )
Это было полезно?

Решение

React components don't destroy themselves. You'd propagate the event to the owner component or rather to the component that holds the data, e.g. as state. Then you'd modify the data and rerender the component.

For example:

var nameRecord = React.createClass({
    handleClick: function(e){
      // propagate event
      if (this.props.onDelete) {
        this.props.onDelete(this.props.data);
      }
    },
    render: function(){
      return <ol onClick={this.handleClick}>{this.props.data.name}</ol>
    }    
});

var people = [{"name":"king"},{"name":"Larry"}];

var NameList = React.createClass({
  getInitialState: function(){
    return { 
        data: people,
    };
  },
  onDelete: function(index) {
    // remove element and update state, which causes a rerender
    var data = this.state.data.slice()
       .splice(this.data.indexOf(person), 1);
    this.setState({data: data});
  },
  render: function(){

    var names = this.state.data.map(function(person){
      return (
        <nameRecord data={person} onDelete={this.onDelete} />
      );
    }.bind(this))

    return (
      <div>
        List of Names - 
        <ul>{names}</ul> 
      </div>
    );
  }

});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top