談談出入React框架踩過的坑


 

1 在JSX的元素中寫入內聯樣式,例如<div style={"color:blue"}></div>

報錯:warning:Style prop value must be an object  react/style-prop-object

原因:在React框架的JSX編碼格式要求,style必須是一個對象

解決方法:除了外部那個表示Javascript語句的花括號外,里面必須再寫一個花括號{}包含的對象,例如<div style={ {  color:“blue”  } }></div>,外部的{ }表示這是Javascript句法,里面的{  }是一個對象

2寫入表格

<table>
   <tr>
       <td></td>
   </tr>
</table>

報錯:Warning: validateDOMNesting(...): <tr> cannot appear as a child of <table>

原因:在React中<tr>元素不可以作為<table>元素的直接子元素

解決方法:在<tr>元素tbody和<table>元素中間插入<tbody>元素,如:

<table>
 <tbody>
   <tr>
       <td></td>
   </tr>
 <tbody>
</table>

3遍歷數組元素:

var arr=[1,2,3]
arr.map(function(x){
            return (<div></div>);
        })

報錯:Warning:Each child in an array or iterator should have a unique "key" prop. Check the render method of `NavBlock`

原因:在React中數組遍歷返回元素或組件時需加上key屬性作為唯一標識

解決方法:寫成

var arr=[1,2,3]
arr.map(function(x,i){
            return (<div key=i></div>);
        })

4在render()函數中返回時這樣寫:

render(){
      return  <div></div>
              <div></div>
              <div></div>
             }

報錯:Adjacent JSX elements must be wrapped in an enclosing tag (75:8)

原因:render()函數中返回的所有元素需要包裹在一個外部元素里面

解決方法:可改寫為:

render(){
      return  <section>
                    <div></div>
                    <div></div>
                    <div></div>
              </section>
         }

最后一點---不能寫成:(return語句和返回元素不在同一行會被解析器視為返回null導致錯誤)

render(){
      return  
                 <section>
                    <div></div>
                    <div></div>
                    <div></div>
                 </section>
             }

 

 

 

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM