反应 - 面试练习 [英] React - interview exercise

查看:40
本文介绍了反应 - 面试练习的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在面试中得到了以下2个组件的React练习,我没有设法让它编译...
问题如下:

I got the following React exercise with 2 components in an interview that I did not manage to make it compile... The question was the following:

更新Counter组件以将onIncrement回调作为props并确保它们独立更新计数器的值。每个回调都应该使用一个整数值作为参数,该值是增加计数器现有值的数量。

代码中的注释但我的问题是如何实现onIncrement功能。

Comments in the code but the my problem is how to implement the "onIncrement" function.

const { Component } = React;
const { render } = ReactDOM;

// state data for 3 counters
const data = [
  { id: 1, value: 1 },
  { id: 2, value: 2 },
  { id: 3, value: 3 }
];

// Counter Component
class Counter extends Component {
  render() {
    const { value } = this.props;
    return (
      <div className="counter">
        <b>{value}</b>
        <div className="counter-controls">
          <button className="button is-danger is-small">-</button>
          //I call the function passed     
          <button className="button is-success is-small" onClick={()=>{onIncrement(this.props.value)}}>+</button>
        </div>
      </div>
    );
  }
}

class App extends Component {
  constructor(props, context) {
    super(props, context);
  }
  
   onIncrement=(value)=>{
   //I tried several things here but I did not manage to make it work. I guess that I need also the id of the object...
   }

  render() {
    return (
      <div>
       
        {data.map(counter => ( 
          <Counter 
            key={counter.id} 
            value={counter.value} 
             //I pass the callback function to the component
            onIncrement={this.onIncrement} 

            />
        ))}
      </div>
    );
  }
}


render(
  <App/>
, document.querySelector('#root'))

推荐答案

我知道答案已被接受,但实际上并没有完全满足要求,即

I know an answer has been accepted, but it doesn't actually satisfy the requirements fully, i.e.


每个回调都应该使用一个整数值作为参数,该值是计数器现有值增加的数量。

Each callback should take a single, integer value as a parameter which is the amount to increment the counter's existing value by.

接受的答案将事件对象作为参数,而不是指定的要求。严格满足预期要求的唯一方法是绑定唯一

The accepted answer takes the event object as a parameter which is not the specified requirement. The only way to strictly satisfy the expected requirement is to bind unique


... onIncrement回调作为道具......

"...onIncrement callbacks as props..."

每个柜台。这种方法有缺点和性能影响这篇文章

for each counter. This approach has drawbacks and performance implications as discussed in this article

工作示例 https://codesandbox.io/s/j2vxj620z9

这篇关于反应 - 面试练习的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆