单击按钮

时间:2019-06-15 23:34:36

标签: reactjs

在单击按钮时尝试删除组件

我已向组件添加了唯一ID,但我无法访问

这是我的主要父组件,单击“删除”按钮时,我试图删除“人”组件

class MyFriends extends Component{

  state = {
    persons: [],
  }

   async componentDidMount( ){
     let response = await axios(`https://randomuser.me/api/?results=1`)
     this.setState(prevState => ({
       persons: [...prevState.persons, ...response.data.results]
     }))
  }

   update = async () => {
    const response = await axios(`https://randomuser.me/api/?results=1`)

    this.setState(prevState => ({
      persons: [...prevState.persons, ...response.data.results]
    }))

  }


  handleDelete = (e) => {
    const test = this.state.persons.splice(-1)
    let oare = this.state.persons.filter( i => i !== test)
    this.setState({
      persons: oare
    })
  }

  updatePerson = (state, first, last, age, email, numar, pic, nat) => {
    const persoana_noua = {
      name: {first: first, last: last},
      dob: {age:age},
      email: email,
      login: {sha1: numar},
      picture: {large:pic},
      nat: nat,
    }

    const proba = this.state.persons
    this.setState(prevState => ({
      persons: [ ...prevState.persons, persoana_noua]
    }))

  }

  remove = (e) => {
    e.persist();
    e.target.value = 1
    // this.setState(prevState => ({
    //   persons: [...this.state.persons.filter(i => i.target.id.value !== test)]
    // }))

     console.log(e.target.id.value)
  }




  render(){

    const test = this.state.persons.map( i =>
      <Person  data={this.state} remove={this.remove} test={this.just_testing} consoleLog={this.updatePerson} key={i.login.sha1} id={Math.random()} first_name={i.name.first} last_name={i.name.last} nat={i.nat}
      picture={i.picture.large} email={i.email} age={i.dob.age}
      />
    )
    return(

      <div className='MyFriends'onClick={this.checkIt} >
      {test}
      <button style={{fontSize: '2em', border: '1px solid green'}} onClick={this.update}>add new friend</button>
      <button style={{fontSize: '2em', border: '1px solid green'}} onClick={this.handleDelete}>delete
      last added friend
      </button>
      <button onClick={this.handleChange}>test</button>
      </div>
    )
  }


}


export default MyFriends;

这是我要删除的子组件,它具有唯一的id和Key,但是我无法访问它,以在状态下使用过滤器


class Person extends Component {
    state={
      modifica : false,
    }

    handleToggle = (e) => {
      this.setState({
        modifica : !this.state.modifica
      })

    }
    handleSubmit = (e) => {

      const first_name  = document.querySelector('.first_name input').value;
      const last_name = document.querySelector('.last_name input').value;
      const age = document.querySelector('.age input').value;
      const email = document.querySelector('.email input').value;
      const numar = Math.random();
      const pic = this.props.picture;
      const nat = this.props.nat;
      e.preventDefault();
      this.props.consoleLog(this.props.data, first_name, last_name, age, email, numar, pic, nat);
      const form = document.querySelector('form')

      this.setState(prevState => ({
        modifica: false,
        persons: [this.props.data]
      }))
      //this.props.test()
    }




    render(props){

      if(this.state.modifica){
        let individ = {}
       individ =
        <div className='Person'>
          <form  name= 'person' onSubmit={this.handleSubmit}>
            <h2 className='first_name'>First Name: <input  name = 'person' type='text'/></h2>
            <h2 className='last_name'>Last Name: <input type='text' /></h2>
            <h3 className='age'>Age: <input type='number' /></h3>
            <img className='flag' src={`https://www.countryflags.io/${this.props.nat}/flat/64.png`}/>
            <img className='pic' src={this.props.picture} />
            <h3 className='email'>email:<input type='text' /></h3>
            <button >Save</button>

          </form>

        </div>
        return individ
      }else{
      const individ =
          <div className='Person'>
            <h2 >First Name: {this.props.first_name} </h2><br/>
            <h2>Last Name: {this.props.last_name}</h2>
            <h3> Age : {this.props.age}</h3>
            <img className='flag' src={`https://www.countryflags.io/${this.props.nat}/flat/64.png`}/>
            <img className='pic' src={this.props.picture} />
            <h3>email: {this.props.email}</h3>
            <button onClick={this.handleToggle}>edit</button>
            <button  onClick={this.props.remove}>remove</button>
          </div>

          return individ
        }
    }
  }
export default Person;

3 个答案:

答案 0 :(得分:0)

好的,所以我检查了您拥有的代码,错误有些微妙,但其核心是e.target是指引发事件的元素,而不是父组件。

如果您在MyFriends组件中修改remove()方法,则会看到错误:

remove = e => {
    e.persist();
    e.target.value = 1;
    // this.setState(prevState => ({
    //   persons: [...this.state.persons.filter(i => i.target.id.value !== test)]
    // }))

    console.log(e);
    console.log(e.target);
    console.log(e.target.id.value);
  };

执行此操作时看到的控制台日志是:

Class {dispatchConfig: Object, _targetInst: FiberNode, nativeEvent: MouseEvent, type: "click", target: HTMLButtonElement…}
<button value="1">remove</button>
undefined

很明显,e.target是指被按下以触发事件的按钮。

要执行预期的操作,您需要找到一种方法来将Person的ID传递到this.props.remove方法中,而不仅仅是传递事件。

一种好方法是使用this.props.id字段来访问此数据。

答案 1 :(得分:0)

您不能使用UNASSIGNED-CoreValidation-Shader-DescriptorTypeMismatch(ERROR / SPEC): msgNum: 0 - Type mismatch on descriptor slot 0.0 (expected `VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT`) but descriptor of type VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER Objects: 1 [0] 0, type: 0, name: NULL UNASSIGNED-CoreValidation-DrawState-DescriptorSetNotUpdated(ERROR / SPEC): msgNum: 0 - Descriptor set 0x52 bound as set #0 encountered the following validation error at vkCmdDrawIndexed() time: Descriptor in binding #0 at global descriptor index 0 requires (none) component type, but bound descriptor format is VK_FORMAT_R8G8B8A8_UNORM. Objects: 1 [0] 0x52, type: 23, name: NULL ... UNASSIGNED-CoreValidation-DrawState-DescriptorSetNotUpdated(ERROR / SPEC): msgNum: 0 - Descriptor set 0xa4 bound as set #0 encountered the following validation error at vkCmdDrawIndexed() time: Descriptor in binding #0 at global descriptor index 0 requires (none) component type, but bound descriptor format is VK_FORMAT_R8G8B8A8_UNORM. Objects: 1 [0] 0xa4, type: 23, name: NULL ,因为您在删除中没有使用任何表单元素。通过ID(人员ID)或使用数组索引访问要删除的项目。

类似的东西应该对您有用。

传递数组索引以删除方法。

npm uninstall -g create-react-app

并修改删除这样的人物道具

e.target.value

答案 2 :(得分:0)

在kiranvj的帮助下,我找到了解决方案(再次是kiranvj),因此我们首先需要选择所按下的“删除”按钮所属的正确组件,然后应用过滤器方法并将所有现有组件与所选组件进行比较,它将返回一个数组,其中不包含我们按下了“删除”按钮的特定Component,并将返回的数组应用于setState。这是代码:

  remove = (index) => {
  let newPersonList = this.state.persons.splice(index, 1); // the item from array
  const proba = this.state.persons.filter(i => i !== newPersonList)
  this.setState({
    persons: proba
  })
  }

我仍在努力了解如何正确选择react.js事件中的元素,因此,如果您有我可以阅读或观看的任何材料以更好地理解概念,请链接