반응: 컴포넌트 함수 내에 "this"가 정의되어 있지 않습니다.
class PlayerControls extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      loopActive: false,
      shuffleActive: false,
    }
  }
  render() {
    var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon"
    return (
      <div className="player-controls">
        <FontAwesome
          className="player-control-icon"
          name='refresh'
          onClick={this.onToggleLoop}
          spin={this.state.loopActive}
        />
        <FontAwesome
          className={shuffleClassName}
          name='random'
          onClick={this.onToggleShuffle}
        />
      </div>
    );
  }
  onToggleLoop(event) {
    // "this is undefined??" <--- here
    this.setState({loopActive: !this.state.loopActive})
    this.props.onToggleLoop()
  }
갱신하고 싶다loopActive상태 전환, 단,this오브젝트가 핸들러에 정의되어 있지 않습니다.튜토리얼 문서에 따르면this컴포넌트를 참조해 주세요.내가 뭘 빼놓았나요?
ES6React.Component메서드는 자동으로 바인드되지 않습니다.네가 직접 묶어놔야 해constructor. 이렇게.
constructor (props){
  super(props);
  
  this.state = {
      loopActive: false,
      shuffleActive: false,
    };
  
  this.onToggleLoop = this.onToggleLoop.bind(this);
}
몇 가지 방법이 있습니다.
하나는 추가이다.this.onToggleLoop = this.onToggleLoop.bind(this);컨스트럭터 안에 있습니다. 
다른 하나는 화살표 기능입니다.onToggleLoop = (event) => {...}.
그리고 거기엔onClick={this.onToggleLoop.bind(this)}.
함수를 다음과 같이 적습니다.
onToggleLoop = (event) => {
    this.setState({loopActive: !this.state.loopActive})
    this.props.onToggleLoop()
}
키워드 바인딩은 fat arrow 함수의 바깥쪽과 안쪽이 동일합니다.이는 호출 시 다른 개체에 바인딩할 수 있는 함수로 선언된 함수와는 다릅니다.이 바인딩을 유지하는 것은 매핑과 같은 조작에 매우 편리합니다.this . something With ( x = > this . do Something With ( x ) 。
렌더링 함수에서 비슷한 바인드를 만나 결국 다음 컨텍스트를 통과했습니다.this다음과 같은 방법으로 합니다.
{someList.map(function(listItem) {
  // your code
}, this)}
사용방법:
{someList.map((listItem, index) =>
    <div onClick={this.someFunction.bind(this, listItem)} />
)}
알아두셔야 합니다this함수가 호출되는 방법에 따라 달라집니다.즉, 함수가 객체의 메서드로 호출되면 함수는this메서드가 호출되는 객체로 설정됩니다.
thisJSX 컨텍스트에서 컴포넌트 오브젝트로서 액세스 할 수 있기 때문에, 다음의 순서로 원하는 메서드를 인라인으로 호출할 수 있습니다.this방법.
함수/메서드에 대한 참조만 전달하면 반응에서 독립 함수로 호출됩니다.
onClick={this.onToggleLoop} // Here you just passing reference, React will invoke it as independent function and this will be undefined
onClick={()=>this.onToggleLoop()} // Here you invoking your desired function as method of this, and this in that function will be set to object from that function is called ie: your component object
내 경우, 이것이 해결책이었다= ( ) = > { }
methodName = (params) => {
//your code here with this.something
}
babel을 사용하는 경우 ES7 bind 연산자 https://babeljs.io/docs/en/babel-plugin-transform-function-bind#auto-self-binding를 사용하여 "this"를 바인딩합니다.
export default class SignupPage extends React.Component {
  constructor(props) {
    super(props);
  }
  handleSubmit(e) {
    e.preventDefault(); 
    const data = { 
      email: this.refs.email.value,
    } 
  }
  render() {
    const {errors} = this.props;
    return (
      <div className="view-container registrations new">
        <main>
          <form id="sign_up_form" onSubmit={::this.handleSubmit}>
            <div className="field">
              <input ref="email" id="user_email" type="email" placeholder="Email"  />
            </div>
            <div className="field">
              <input ref="password" id="user_password" type="new-password" placeholder="Password"  />
            </div>
            <button type="submit">Sign up</button>
          </form>
        </main>
      </div>
    )
  }
}
componentDidMount 등의 라이프 사이클 메서드로 작성한 메서드를 호출하면...이 경우 사용할 수 있는 것은this.onToggleLoop = this.onToogleLoop.bind(this)뚱뚱한 화살표 기능onToggleLoop = (event) => {...}.
생성자에서 함수를 선언하는 일반적인 접근 방식은 라이프사이클 메서드가 더 일찍 호출되었기 때문에 작동하지 않습니다.
제 경우 forwardRef를 사용하여 ref를 수신한 스테이트리스 컴포넌트의 경우 https://itnext.io/reusing-the-ref-from-forwardref-with-react-hooks-4ce9df693dd에 기재되어 있는 절차를 수행해야 합니다.
여기서부터(onClick은 'this'에 해당하는 항목에 액세스할 수 없음)
const Com = forwardRef((props, ref) => {
  return <input ref={ref} onClick={() => {console.log(ref.current} } />
})
이것에 대해서(효과 있음)
const useCombinedRefs = (...refs) => {
  const targetRef = React.useRef()
  useEffect(() => {
    refs.forEach(ref => {
      if (!ref) return
      if (typeof ref === 'function') ref(targetRef.current)
      else ref.current = targetRef.current
    })
  }, [refs])
  return targetRef
}
const Com = forwardRef((props, ref) => {
  const innerRef = useRef()
  const combinedRef = useCombinedRefs(ref, innerRef)
  return <input ref={combinedRef } onClick={() => {console.log(combinedRef .current} } />
})
render() 메서드에서 onToggleLoop 메서드를 호출하는 방법을 다시 쓸 수 있습니다.
render() {
    var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon"
return (
  <div className="player-controls">
    <FontAwesome
      className="player-control-icon"
      name='refresh'
      onClick={(event) => this.onToggleLoop(event)}
      spin={this.state.loopActive}
    />       
  </div>
    );
  }
React 매뉴얼에서는 Atribute의 식에서 함수에 콜을 발신할 때의 이 패턴을 나타내고 있습니다.
 그런지 을 해드릴게요.this정의되어 있지 않습니다.
를 사용하는 this기능이 에서, 화살표 기능이 아닌 기능thismode strict 、 로닌,,,, but  but,, but ,,,,, , ,,,, 로 하면 mode,,,,모드로this정의되지 않습니다(https://www.w3schools.com/js/js_this.asp)).
또한 ES6 모듈은 항상 strict 모드입니다(javascript: 모듈 내부에서는 strict 사용이 불필요합니다).
 수 요.thisonToggleLoop로서 PlayerControls(컴포넌트 )bind다음 중 하나:
constructor(props) {
    super(props)
    this.state = {
      loopActive: false,
      shuffleActive: false,
    }
    this.onToggleLoop = this.onToggleLoop.bind(this)
}
또는 화살표 기능을 대신 사용합니다.
onToggleLoop = (event) => {
    this.setState({loopActive: !this.state.loopActive})
    this.props.onToggleLoop()
}
가 없기 에, 「」는 「컨텍스트」this화살표 함수는 화살표 함수를 정의한 개체를 나타냅니다.
언급URL : https://stackoverflow.com/questions/33973648/react-this-is-undefined-inside-a-component-function
'programing' 카테고리의 다른 글
| PHP 배열이 연관성이 있는지 순차적인지 확인하는 방법 (0) | 2022.10.27 | 
|---|---|
| useEffect 후크 내부의 상태를 설정할 수 있습니까? (0) | 2022.10.27 | 
| 잭슨과 롬복에게 함께 일하게 할 수 없다. (0) | 2022.10.27 | 
| JavaScript 개체의 내용을 인쇄하시겠습니까? (0) | 2022.10.27 | 
| 잘못된 날짜/시간 형식: 1366 잘못된 문자열 값 (0) | 2022.10.27 |