programing

어떻게 조건부로의 반응 요소들에 특성을 추가하니?

prostudy 2022. 9. 19. 23:14
반응형

어떻게 조건부로의 반응 요소들에 특성을 추가하니?

있는 방법 특정한 조건이 충족되는 것의 반응 요소에 특성을 추가하니?

폼 및 readOnly Atribut을 "readOnly" 때문에 이 알 수.readOnly="false"완전히 특성을 생략하는 것과 같지 않은가.

이 예제 아래 내가 원하는데 그게 잘 안됐는지 설명해야 한다.

(Parse오류:예상치 못한 식별자)

function MyInput({isRequired}) {
  return <input classname="foo" {isRequired ? "required" : ""} />
}

네가 지난 값truthy지 않다 듣자 하니, 특정 특성에 대한의 반응 지적인 특성을 생략하기에 충분하다.예를 들어:

const InputComponent = function() {
    const required = true;
    const disabled = false;

    return (
        <input type="text" disabled={disabled} required={required} />
    );
}

결과를 초래할 것이다:

<input type="text" required>

:누가 how/why 이 일이 일어났는 지에 호기심이 많다고, ReactDOM의 소스 코드에 선 30과 167은 DOMProperty.js 파일 구체적으로에서 정보를 사용할 수 있Update를 설정합니다.

Juandemarco의 해답은 보통이지만 여기 다른 선택은 정확하다.

: 어떻게 같은 물체를 건설한다.

var inputProps = {
  value: 'foo',
  onChange: this.handleChange
};

if (condition) {
  inputProps.disabled = true;
}

밥 흐름에 따라 선택적으로 또한 다른 소도구에 전달합니다.

<input
    value="this is overridden by inputProps"
    {...inputProps}
    onChange={overridesInputProps}
 />

여기 React-Bootstrap(버전 0.32.4)을 통해 Bootstrap의 버튼 사용에 대한 예제: 있다.

var condition = true;

return (
  <Button {...(condition ? {bsStyle: 'success'} : {})} />
);

, 「」의 어느쪽인가를 선택할 수 있습니다.{bsStyle: 'success'} ★★★★★★★★★★★★★★★★★」{}이렇게 , 된 물건의 전파 합니다.Button하지 않기 컴포넌트에는 되지 않습니다.false는 반환된 오브젝트에 속성이 존재하지 않습니다.


Andy Polhill의 코멘트에 근거한 대체 방법:

var condition = true;

return (
  <Button bsStyle={condition ? 'success' : undefined} />
);

는 두 컴포넌트 " " " 입니다.<Button/>의 »props에는 키가 .bsStyle 「」으로undefined.

여기 대안이 있다.

var condition = true;

var props = {
  value: 'foo',
  ...(condition && { disabled: true })
};

var component = <div {...props} />;

또는 인라인 버전

var condition = true;

var component = (
  <div value="foo" {...(condition && { disabled: true })} /> 
);

내가 하는 방법은 이렇다.

조건부여:

<Label
    {...{
      text: label,
      type,
      ...(tooltip && { tooltip }),
      isRequired: required
    }}
/>

조건부가 없는 경우 (내 생각에) 더 읽기 쉽기 때문에 저는 여전히 일반적인 소품 전달 방식을 선호한다.

조건 없이:

<Label text={label} type={type} tooltip={tooltip} isRequired={required} />

조건이 true인 경우 커스텀 속성을 추가합니다(aria-* 또는 data-* 사용).

{...this.props.isTrue && {'aria-name' : 'something here'}}

조건이 참일 경우 스타일 속성을 추가한다고 가정합니다.

{...this.props.isTrue && {style : {color: 'red'}}}

)의 할 수 .{isVisible && <SomeComponent />}를 참조해 주세요.

class MyComponent extends React.Component {
  render() {
    return (
      <div someAttribute={someCondition && someValue} />
    );
  }
}

ECMAScript 6을 사용하면 이렇게 간단하게 쓸 수 있습니다.

// First, create a wrap object.
const wrap = {
    [variableName]: true
}
// Then, use it
<SomeComponent {...{wrap}} />

「」를 사용합니다.undefined합니다: works works 、 works works 、 works works works works works works works 。

const name = "someName";

return (
    <input name={name ? name : undefined} />
);

Ajax 콜 후에 상태가 변화하고 부모 컴포넌트가 다시 렌더링되기 때문에 이 방법은 동작합니다.

render : function () {
    var item;
    if (this.state.isRequired) {
        item = <MyOwnInput attribute={'whatever'} />
    } else {
        item = <MyOwnInput />
    }
    return (
        <div>
            {item}
        </div>
    );
}

예를 들어 사용자 정의 컨테이너에 특성 스타일 사용

const DriverSelector = props => {
  const Container = props.container;
  const otherProps = {
    ...( props.containerStyles && { style: props.containerStyles } )
  };

  return (
    <Container {...otherProps} >
  1. React [1]에 나열된 일부 부울 속성의 경우:
<input disabled={disabled} />

// renders either `<input>` or `<input disabled>` 
  1. 기타 Atribute의 경우:
<div aria-selected= {selected ? "" : undefined} />

// renders either `<div aria-selected></div>` or `<div></div>`

[1] 부울 속성 목록:https://github.com/facebook/react/blob/3f9480f0f5ceb5a32a3751066f0b8e9eae5f1b10/packages/react-dom/src/shared/DOMProperty.js#L318-L345

반응에서 구성요소를 조건부로 렌더링할 수 있지만 소품, className, id 등의 특성도 렌더링할 수 있습니다.

반응에서는 구성요소를 조건부로 렌더링하는 데 도움이 되는 3진 연산자를 사용하는 것이 좋습니다.

또한 구성요소 및 구성요소의 스타일 속성을 조건부로 렌더링하는 방법도 보여 줍니다.

다음으로 간단한 예를 제시하겠습니다.

class App extends React.Component {
  state = {
    isTrue: true
  };

  render() {
    return (
      <div>
        {this.state.isTrue ? (
          <button style={{ color: this.state.isTrue ? "red" : "blue" }}>
            I am rendered if TRUE
          </button>
        ) : (
          <button>I am rendered if FALSE</button>
        )}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

제 관점에서는 여러 개의 조건부 소품을 관리하는 가장 좋은 방법은 @brigand의 소품 오브젝트 접근입니다.단, 추가되는 것을 피하기 위해 개선할 수 있습니다.if각 조건부 지지대에 대한 블록.

ifVal 도우미

원하는 대로 이름을 변경합니다(iv, condVal, cv, _, ...).

도우미 함수를 정의하여 값을 반환하거나 조건이 충족되면 다른 값을 반환할 수 있습니다.

// components-helpers.js
export const ifVal = (cond, trueValue=true, falseValue=null) => {
  return cond ? trueValue : falseValue
}

한다면condtrue(또는 truthy),trueValue반환됨 - 또는true.한다면condfalse(또는 가짜),falseValue반환됨 - 또는null.

이러한 디폴트(true그리고.null)는 보통 Prop를 React 컴포넌트에 전달하거나 전달하지 않는 올바른 값입니다.이 함수는 "개선된 반응 3원 연산자"로 생각할 수 있습니다.반환된 값에 대한 제어가 더 필요한 경우 개선하십시오.

여러 가지 소품과 함께 사용합시다.

(복잡한) 소품 오브젝트 작성

// your-code.js
import { ifVal } from './components-helpers.js'

// BE SURE to replace all true/false with a real condition in you code
// this is just an example

const inputProps = {
  value: 'foo',
  enabled: ifVal(true), // true
  noProp: ifVal(false), // null - ignored by React
  aProp: ifVal(true, 'my value'), // 'my value'
  bProp: ifVal(false, 'the true text', 'the false text') // 'my false value',
  onAction: ifVal(isGuest, handleGuest, handleUser) // it depends on isGuest value
};

 <MyComponent {...inputProps} />

이 접근법은 클래스 이름 유틸리티를 사용하여 클래스를 조건부로 관리하는 일반적인 방법과 비슷하지만 소품에 맞게 조정되었습니다.

이 방법을 사용해야 하는 이유

많은 조건부 소품이라도 깔끔하고 읽기 쉬운 구문을 얻을 수 있습니다.새로운 소품마다 오브젝트 선언 안에 코드 한 줄만 추가됩니다.

이 방법으로 반복 연산자의 구문 노이즈를 바꿉니다(...,&&,? :소품이나 기능 호출이 많은 경우, 매우 귀찮을 수 있습니다.

개발자로서 우리의 최우선 과제는 문제를 해결하는 가장 명백한 코드를 작성하는 것입니다.너무 많은 경우 우리는 자존심을 위해 문제를 해결하고 필요하지 않은 부분에 복잡성을 더합니다.우리의 코드는 오늘날, 내일, 그리고 우리의 동료들에게 간단해야 합니다.

우리가 뭔가를 할 수 있다고 해서

늦은 답변이 도움이 되었으면 합니다.

<input checked={true} type="checkbox"  />

리액트 기능 컴포넌트에서는 이와 같은 것을 시도하여 불필요한 태그 속성을 생략할 수 있습니다.

<div className="something" ref={someCondition ? dummyRef : null} />

ref, class 등의 태그를 생략할 필요가 있는 경우에는 이 방법으로 대응합니다.하지만 그게 모든 태그 속성에 적용되는지는 모르겠지만

<Button {...(isWeb3Enabled ? {} : { isExternal: true })}>
    Metamask
</Button>

포스트 JSX In Deepth를 고려하면 다음과 같은 방법으로 문제를 해결할 수 있습니다.

if (isRequired) {
  return (
    <MyOwnInput name="test" required='required' />
  );
}
return (
    <MyOwnInput name="test" />
);

속성의 값을 함수로 하고 싶은 사람에게 도움이 될 것 같습니다.

import { RNCamera } from 'react-native-camera';
[...]

export default class MyView extends React.Component {

    _myFunction = (myObject) => {
        console.log(myObject.type); //
    }

    render() {

        var scannerProps = Platform.OS === 'ios' ? 
        {
            onBarCodeRead : this._myFunction
        } 
        : 
        { 
            // here you can add attribute(s) for other platforms
        }

        return (
            // it is just a part of code for MyView's layout
            <RNCamera 
                ref={ref => { this.camera = ref; }}
                style={{ flex: 1, justifyContent: 'flex-end', alignItems: 'center', }}
                type={RNCamera.Constants.Type.back}
                flashMode={RNCamera.Constants.FlashMode.on}
                {...scannerProps}
            />
        );
    }
}

쉽게

const InputText= ({required = false , disabled = false, ...props}) => 
         (<input type="text" disabled={disabled} required={required} {...props} />);

이렇게 해서

<InputText required disabled/>

변수 " " " 가 지정됨isRequired렌더링 메서드(클래스를 사용하는 경우) 또는 반환 스테이트먼트(함수 컴포넌트를 사용하는 경우)에서 다음 작업을 수행할 수 있습니다.

 <MyComponent required={isRequired ? 'true' : undefined} />

React에서는 Propes로 부모에서 자녀로 값을 전달합니다.값이 거짓일 경우 소품으로 전달되지 않습니다.또한 상황에 따라 3진수(조건 연산자)를 사용할 수도 있습니다.

언급URL : https://stackoverflow.com/questions/31163693/how-do-i-conditionally-add-attributes-to-react-components

반응형