Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

reactjs - Convert a React Class Component to a Function Component

Did I convert class component to function component correctly btw?

I don't know how to convert these code to function component tho, plz correct me

I don't necessarily need a code, just explain what I was wrong and what react knowledge I was missing

This is an original class component

const eventNames = ['onDragStart', 'onDrag', 'onDragEnd'];

function round5(value) {
  return (Math.round(value * 1e5) / 1e5).toFixed(5);
}

export default class ControlPanel extends PureComponent {
  renderEvent = eventName => {
    const {events = {}} = this.props;
    const lngLat = events[eventName];
    return (
      <div key={eventName}>
        <strong>{eventName}:</strong> {lngLat ? lngLat.map(round5).join(', ') : <em>null</em>}
      </div>
    );
  };

  render() {
    return (
      <div className="control-panel">
        <h3>Draggable Marker</h3>
        <p>Try dragging the marker to another location.</p>
        <div>{eventNames.map(this.renderEvent)}</div>
      </div>
    );
  }
}

This is a code I converted to function component

function round5(value) {
  return (Math.round(value * 1e5) / 1e5).toFixed(5);
}

const ControlPanel = (props) => {
  const eventNames = ["onDragStart", "onDrag", "onDragEnd"];

  function renderEvent(eventName) {
    const { events } = props;
    const lngLat = events[eventName];

    return (
      <div key={eventName}>
        <strong>{eventName}:</strong>{" "}
        {lngLat ? lngLat.map(round5).join(", ") : <em>null</em>}
      </div>
    );
  }  

  return (
      <div className="control-panel">
        <h3>Draggable Marker</h3>
        <p>Try dragging the marker to another location.</p>
        <div>{eventNames.map(eventName => renderEvent(eventName))}</div>
      </div>
  );
};

export default ControlPanel;

question from:https://stackoverflow.com/questions/65847402/convert-a-react-class-component-to-a-function-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can reduce code a bit: <div>{eventNames.map(renderEvent)}</div>

but renderEvent is not a react component so it has no this.props


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...