簡體   English   中英

如何在 React js 中單擊復選框時啟用/禁用按鈕?

[英]How to enable/disable a button on click of a checkbox in React js?

有人可以幫我處理這段代碼嗎?我研究了很多,我被困住了。

class App extends Component{
   constructor(props){
     super(props);
    this.isChecked=this.isChecked.bind(this);
   }
 }
 isChecked = (chk,sub1) => {
   var btn = document.getElementById(sub1);
     if (chk.checked == true) {
         btn.disabled = false;
     } else {
         btn.disabled = true;
     };
  
 }



function App(){         
return(
     <form>
    <div className='check'>
      <input 
      type='checkbox'
      className='checkbox'
      id='termschkbx'
      onchange="isChecked(this,'sub1')"
      />
      
      <span>I agree to Terms & Conditions.<a href="" className='readme'>Read here</a> </span>
    </div>
    <div>


    <button
    type="submit"
     id="sub1"
     disabled='disabled'
     className=" createaccount" 
     type="submit">CREATE ACCOUNT</button>
    </div>
    </form>
)
}

如何解決這個問題?

錯誤:標識符“App”已被聲明。

有沒有有效的方法來做到這一點?

有什么方法可以設置我的提交按鈕的樣式嗎? (即)它應該在禁用時具有一種特定的顏色,而在啟用時應該具有一種特定的顏色。

有一個 CSS 選擇器:disabled ,當它被禁用時,您可以使用它來設置按鈕的樣式。

看起來您還沒有使用任何 CSS 解決方案,我建議您使用CSSModule樣式組件

錯誤:標識符“App”已被聲明。

您正在定義App兩次:

class App extends Component { ...
function App(){ ...

刪除一個並解決錯誤,但根據上下文,您可能應該將function App()的內容移動到 function render()中的class App

另外,我不建議混合匹配 React 其他框架

So you can achieve the functionality using the state in the App component.
class App extends Component{
   constructor(props){
     super(props);
    this.state={isHidden : false } // button will not be hidden initally.
   }
 }
 isChecked = () => {
  this.setState((state)=>({isHidden : !state.isHidden})) /* we're setting the state value isHidden equal to the negation of previous value of isHidden onChange event of checkbox */
 }

render(){
return(
     <form>
    <div className='check'>
      <input 
      type='checkbox'
      className='checkbox'
      id='termschkbx'
      onChange={this.isChecked}
      />
      
      <span>I agree to Terms & Conditions.<a href="" className='readme'>Read here</a> </span>
    </div>
    <div>


    {this.state.isHidden && <button
    type="submit"
     id="sub1"
     className=" createaccount" 
     type="submit">CREATE ACCOUNT</button> }
    </div>
    </form>
)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM