programming study/F-React, Typescript

20220427_react(onClick 사용법)

gu9gu 2022. 4. 27. 15:16

react - onClick

 

1. 버튼 눌렀을 때만 1출력되게 하고 싶을 때

import React, {useState,useEffect} from 'react';

const Test = () => {
    const fnTest = () => {
        console.log(1);
    }
    const fnTestA =() => (event) => {
        console.log(1);
    }
    
    return (
       <div>
          <button onClick={() => fnTest()}>버튼 눌렀을 때만 1 출력</button>
          {/* <button onClick={fnTest()}>화면 렌더링 되면서 1 출력, 버튼 동작 안 함</button> */}
          {/* <button onClick={fnTestA()}>버튼 눌렀을 때만 1 출력</button> */}
          {/* <button onClick={(e) => fnTest(e)}>버튼 눌렀을 때만 1 출력</button> */}
          {/* <button onClick={() => fnTest()}>버튼 눌렀을 때만 1 출력</button> */}
       </div>
    );
};

export default Test;

 

2. 객체 배열을 수정하는 법

let newArray = [...배열];

newArray[인덱스] 사용++; // 인덱스 사용해서 제어

set함수(newArray);

 

참고  https://stackoverflow.com/questions/55987953/how-do-i-update-states-onchange-in-an-array-of-object-in-react-hooks

 

How do I update states `onChange` in an array of object in React Hooks

I have retrieved datas stored using useState in an array of object, the datas was then outputted into form fields. And now I want to be able to update the fields (state) as I type. I have seen exam...

stackoverflow.com

import React, {useState,useEffect} from 'react';

const Test = () => {
    const [places, setPlaces] = useState([
        {id:1, val:0},
        {id:2, val:0}
    ]);
	
    const fnGoodA = (idx) => {
        let newArray = [...places];
        newArray[idx].val ++;
        
        setPlaces(newArray);
    }
    const fnGoodB = (idx) => (evnet) => {
        let newArray = [...places];
        newArray[idx].val ++;
        
        setPlaces(newArray);
    }
    const fnGoodC = (idx) => {
        let newArray = [...places];
        newArray[idx].val ++;
        
        setPlaces(newArray);
    }
    
    return (
       <div>
          {places.map( (item, idx) => (
          	<div key={idx}>
            	<span>{item.val}<span>
            	<button onclick={fnGoodA(idx)}>(잘못된 방법) 무한 반복됨. infinite loop. </button>
                {/* <button onclick={()=>fnGoodA(idx)}>버튼 누르면 + 1</button> */}
                {/* <button onclick={fnGoodB(idx)}>버튼 누르면 +1</button> */}
                {/* <button onclick={(event)=>fnGoodC(idx,event)}>버튼 누르면 + 1</button> */}
            </div>
          ))}
          	
       </div>
    );
};

export default Test;

 

'programming study > F-React, Typescript' 카테고리의 다른 글

20220508_react_import  (0) 2022.05.08
20220506_react_import  (0) 2022.05.06
20220420_react_useEffect  (0) 2022.04.22