Hướng dẫn innerhtml reactjs - innerhtml reactjs

React áp dụng hệ thống DOM không phụ thuộc vào trình duyệt để tăng hiệu suất và độ tương thích với nhiều trình duyệt khác nhau. Nhân dịp này, chúng tôi đã loại bỏ một số khía cạnh chưa hoàn chỉnh trong cách triển khai DOM trên trình duyệt.

Nội dung chính

  • Sự khác biệt trong các thuộc tính
  • dangerouslySetInnerHTML
  • suppressContentEditableWarning
  • suppressHydrationWarning
  • Tất cả thuộc tính HTML được hỗ trợ

Nội dung chính

  • Sự khác biệt trong các thuộc tính
  • dangerouslySetInnerHTML
  • suppressContentEditableWarning
  • suppressHydrationWarning
  • Tất cả thuộc tính HTML được hỗ trợ

Trong React, tất cả các thuộc tính của DOM (bao gồm xử lí sự kiện) phải được viết theo camelCase. Ví dụ như attribute tabindex, thì trong React là tabIndex. Có những ngoại lệ là thuộc tính aria-*

const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!div>;
}
0 phải được viết chữ thường. Ví dụ
const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!div>;
}
1 vẫn là
const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!div>;
}
1.

Sự khác biệt trong các thuộc tính

dangerouslySetInnerHTML

suppressContentEditableWarning

suppressHydrationWarning

Tất cả thuộc tính HTML được hỗ trợ

Trong React, tất cả các thuộc tính của DOM (bao gồm xử lí sự kiện) phải được viết theo camelCase. Ví dụ như attribute tabindex, thì trong React là tabIndex. Có những ngoại lệ là thuộc tính aria-*

const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!div>;
}
0 phải được viết chữ thường. Ví dụ
const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!div>;
}
1 vẫn là
const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!div>;
}
1.

Có một vài thuộc tính hoạt động khác biệt giữa React và HTML:

dangerouslySetInnerHTML

suppressContentEditableWarning

function createMarkup() {
  return {__html: 'First · Second'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

suppressHydrationWarning

Tất cả thuộc tính HTML được hỗ trợ

Trong React, tất cả các thuộc tính của DOM (bao gồm xử lí sự kiện) phải được viết theo camelCase. Ví dụ như attribute tabindex, thì trong React là tabIndex. Có những ngoại lệ là thuộc tính aria-* và const divStyle = { color: 'blue', backgroundImage: 'url(' + imgUrl + ')', }; function HelloWorldComponent() { return
Hello World!
; }0 phải được viết chữ thường. Ví dụ const divStyle = { color: 'blue', backgroundImage: 'url(' + imgUrl + ')', }; function HelloWorldComponent() { return
Hello World!
; }1 vẫn là const divStyle = { color: 'blue', backgroundImage: 'url(' + imgUrl + ')', }; function HelloWorldComponent() { return
Hello World!
; }1.

Có một vài thuộc tính hoạt động khác biệt giữa React và HTML:

checked

Thuộc tính

const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!div>;
}
3 được hỗ trợ bởi các component
const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!div>;
}
4 với kiểu
const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!div>;
}
5 hoặc
const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!div>;
}
6. Bạn có thể dùng nó để thiết lập cho component có được checked hay chưa. Điều này hữu ích khi xây dựng những Component Kiểm Soát.
const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!div>;
}
7 là giá trị không kiểm soát, nó sẽ quyết định component có được chọn hay không khi nó được mount lần đầu tiên.

className

Để đặt class css, sử dụng thuộc tính className. Nó được sử dụng cho tất cả các phần tử DOM và SVG như

const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!div>;
}
8,
const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!div>;
}
9 và những thuộc tính khác.

Nếu bạn sử dụng React với Web Components (trường hợp không phổ biến), thì vẫn dùng

const divStyle = {
  WebkitTransition: 'all', // nhớ là chữ 'W' được viết hoa
  msTransition: 'all' // 'ms' là tiền tố duy nhất được viết thường
};

function ComponentWithTransition() {
  return <div style={divStyle}>This should work cross-browserdiv>;
}
0.sử dụng thuộc tính
// Result style: '10px'
<div style={{ height: 10 }}>
  Hello World!
div>

// Result style: '10%'
<div style={{ height: '10%' }}>
  Hello World!
div>
5 trực tiếp không được khuyến khích .
Trong đa số các trường hợp,
// Result style: '10px'
<div style={{ height: 10 }}>
  Hello World!
div>

// Result style: '10%'
<div style={{ height: '10%' }}>
  Hello World!
div>
7 nên được dùng cùng với một file CSS rời để style. Thuộc tính
// Result style: '10px'
<div style={{ height: 10 }}>
  Hello World!
div>

// Result style: '10%'
<div style={{ height: '10%' }}>
  Hello World!
div>
5 thường được dùng trong React để trỏ tới những class được định nghiã ở stylesheet css bên ngoài. Xem thêm FAQ: Styling and CSS.

const divStyle = {
  WebkitTransition: 'all', // nhớ là chữ 'W' được viết hoa
  msTransition: 'all' // 'ms' là tiền tố duy nhất được viết thường
};

function ComponentWithTransition() {
  return <div style={divStyle}>This should work cross-browserdiv>;
}
1 tương đương với
const divStyle = {
  WebkitTransition: 'all', // nhớ là chữ 'W' được viết hoa
  msTransition: 'all' // 'ms' là tiền tố duy nhất được viết thường
};

function ComponentWithTransition() {
  return <div style={divStyle}>This should work cross-browserdiv>;
}
2 trong DOM. Nhìn chung, việc thay đổi DOM từ Javascript khá rủi ro do nó có thể vô tình để lộ người dùng cross-site scripting (XSS). Vì vậy, React có thể tạo HTML trực tiếp, nhưng bạn phải sử dụng
const divStyle = {
  WebkitTransition: 'all', // nhớ là chữ 'W' được viết hoa
  msTransition: 'all' // 'ms' là tiền tố duy nhất được viết thường
};

function ComponentWithTransition() {
  return <div style={divStyle}>This should work cross-browserdiv>;
}
1 và truyền một object với key là
const divStyle = {
  WebkitTransition: 'all', // nhớ là chữ 'W' được viết hoa
  msTransition: 'all' // 'ms' là tiền tố duy nhất được viết thường
};

function ComponentWithTransition() {
  return <div style={divStyle}>This should work cross-browserdiv>;
}
4 để nhăc bạn nhớ rằng điều này không an toàn. Ví dụ:

const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!div>;
}

htmlFor

const divStyle = {
  WebkitTransition: 'all', // nhớ là chữ 'W' được viết hoa
  msTransition: 'all' // 'ms' là tiền tố duy nhất được viết thường
};

function ComponentWithTransition() {
  return <div style={divStyle}>This should work cross-browserdiv>;
}

Do

const divStyle = {
  WebkitTransition: 'all', // nhớ là chữ 'W' được viết hoa
  msTransition: 'all' // 'ms' là tiền tố duy nhất được viết thường
};

function ComponentWithTransition() {
  return <div style={divStyle}>This should work cross-browserdiv>;
}
5 là một từ khoá trong Javascript, React dùng
const divStyle = {
  WebkitTransition: 'all', // nhớ là chữ 'W' được viết hoa
  msTransition: 'all' // 'ms' là tiền tố duy nhất được viết thường
};

function ComponentWithTransition() {
  return <div style={divStyle}>This should work cross-browserdiv>;
}
6.

onChange

// Result style: '10px'
<div style={{ height: 10 }}>
  Hello World!
div>

// Result style: '10%'
<div style={{ height: '10%' }}>
  Hello World!
div>

Sự kiện

const divStyle = {
  WebkitTransition: 'all', // nhớ là chữ 'W' được viết hoa
  msTransition: 'all' // 'ms' là tiền tố duy nhất được viết thường
};

function ComponentWithTransition() {
  return <div style={divStyle}>This should work cross-browserdiv>;
}
7 hoạt động đúng như tên gọi của nó: khi một giá trị của trường mẫu bị thay đổi, sự kiện này được phát ra. Chúng tôi cố tình không sử dụng hành vi của trình duyệt bởi vì
const divStyle = {
  WebkitTransition: 'all', // nhớ là chữ 'W' được viết hoa
  msTransition: 'all' // 'ms' là tiền tố duy nhất được viết thường
};

function ComponentWithTransition() {
  return <div style={divStyle}>This should work cross-browserdiv>;
}
7 được hiểu sai bởi chính hành vi của nó và React dựa vào sự kiện này để xử lý đầu vào của người dùng trong thời gian thực.

suppressContentEditableWarning

suppressHydrationWarning

suppressHydrationWarning

Tất cả thuộc tính HTML được hỗ trợ

Nếu bạn để

<div tabIndex={-1} />      // Just like node.tabIndex DOM API
<div className="Button" /> // Just like node.className DOM API
<input readOnly={true} />  // Just like node.readOnly DOM API
9 là
accept acceptCharset accessKey action allowFullScreen alt async autoComplete
autoFocus autoPlay capture cellPadding cellSpacing challenge charSet checked
cite classID className colSpan cols content contentEditable contextMenu controls
controlsList coords crossOrigin data dateTime default defer dir disabled
download draggable encType form formAction formEncType formMethod formNoValidate
formTarget frameBorder headers height hidden high href hrefLang htmlFor
httpEquiv icon id inputMode integrity is keyParams keyType kind label lang list
loop low manifest marginHeight marginWidth max maxLength media mediaGroup method
min minLength multiple muted name noValidate nonce open optimum pattern
placeholder poster preload profile radioGroup readOnly rel required reversed
role rowSpan rows sandbox scope scoped scrolling seamless selected shape size
sizes span spellCheck src srcDoc srcLang srcSet start step style summary
tabIndex target title type useMap value width wmode wrap
0, React sẽ không cảnh báo về những sự không trùng khớp trong những thuộc tính và nội dung của element đó. Nó chỉ hoạt động một cấp, và được dự định sử dụng như một lối thoát. Đừng lạm dụng nó. Bạn có thể xem thêm về hydration tại
accept acceptCharset accessKey action allowFullScreen alt async autoComplete
autoFocus autoPlay capture cellPadding cellSpacing challenge charSet checked
cite classID className colSpan cols content contentEditable contextMenu controls
controlsList coords crossOrigin data dateTime default defer dir disabled
download draggable encType form formAction formEncType formMethod formNoValidate
formTarget frameBorder headers height hidden high href hrefLang htmlFor
httpEquiv icon id inputMode integrity is keyParams keyType kind label lang list
loop low manifest marginHeight marginWidth max maxLength media mediaGroup method
min minLength multiple muted name noValidate nonce open optimum pattern
placeholder poster preload profile radioGroup readOnly rel required reversed
role rowSpan rows sandbox scope scoped scrolling seamless selected shape size
sizes span spellCheck src srcDoc srcLang srcSet start step style summary
tabIndex target title type useMap value width wmode wrap
1.

value

Thuộc tính

// Result style: '10px'
<div style={{ height: 10 }}>
  Hello World!
div>

// Result style: '10%'
<div style={{ height: '10%' }}>
  Hello World!
div>
3 được hỗ trợ bởi những component
const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!div>;
}
4,
accept acceptCharset accessKey action allowFullScreen alt async autoComplete
autoFocus autoPlay capture cellPadding cellSpacing challenge charSet checked
cite classID className colSpan cols content contentEditable contextMenu controls
controlsList coords crossOrigin data dateTime default defer dir disabled
download draggable encType form formAction formEncType formMethod formNoValidate
formTarget frameBorder headers height hidden high href hrefLang htmlFor
httpEquiv icon id inputMode integrity is keyParams keyType kind label lang list
loop low manifest marginHeight marginWidth max maxLength media mediaGroup method
min minLength multiple muted name noValidate nonce open optimum pattern
placeholder poster preload profile radioGroup readOnly rel required reversed
role rowSpan rows sandbox scope scoped scrolling seamless selected shape size
sizes span spellCheck src srcDoc srcLang srcSet start step style summary
tabIndex target title type useMap value width wmode wrap
4 và
accept acceptCharset accessKey action allowFullScreen alt async autoComplete
autoFocus autoPlay capture cellPadding cellSpacing challenge charSet checked
cite classID className colSpan cols content contentEditable contextMenu controls
controlsList coords crossOrigin data dateTime default defer dir disabled
download draggable encType form formAction formEncType formMethod formNoValidate
formTarget frameBorder headers height hidden high href hrefLang htmlFor
httpEquiv icon id inputMode integrity is keyParams keyType kind label lang list
loop low manifest marginHeight marginWidth max maxLength media mediaGroup method
min minLength multiple muted name noValidate nonce open optimum pattern
placeholder poster preload profile radioGroup readOnly rel required reversed
role rowSpan rows sandbox scope scoped scrolling seamless selected shape size
sizes span spellCheck src srcDoc srcLang srcSet start step style summary
tabIndex target title type useMap value width wmode wrap
5. Ban có thể sử dụng nó để đặt giá trị của component. Điều này là cần thiết để tạo Component Kiểm Soát.
accept acceptCharset accessKey action allowFullScreen alt async autoComplete
autoFocus autoPlay capture cellPadding cellSpacing challenge charSet checked
cite classID className colSpan cols content contentEditable contextMenu controls
controlsList coords crossOrigin data dateTime default defer dir disabled
download draggable encType form formAction formEncType formMethod formNoValidate
formTarget frameBorder headers height hidden high href hrefLang htmlFor
httpEquiv icon id inputMode integrity is keyParams keyType kind label lang list
loop low manifest marginHeight marginWidth max maxLength media mediaGroup method
min minLength multiple muted name noValidate nonce open optimum pattern
placeholder poster preload profile radioGroup readOnly rel required reversed
role rowSpan rows sandbox scope scoped scrolling seamless selected shape size
sizes span spellCheck src srcDoc srcLang srcSet start step style summary
tabIndex target title type useMap value width wmode wrap
6 là thuộc tính tương đương trong Component Không Kiểm Soát, nó đặt giá trị cho Component khi nó được mount lần đầu tiên.

Tất cả thuộc tính HTML được hỗ trợ

Trong React 16, tất cả thuộc tính DOM đều được hỗ trợ.

React luôn cung cấp một API với trọng tâm là javascript cho DOM. Bời vì những React component thường nhận những props được tuỳ chỉnh hoặc có liên quan tới DOM, React sử dụng quy ước

accept acceptCharset accessKey action allowFullScreen alt async autoComplete
autoFocus autoPlay capture cellPadding cellSpacing challenge charSet checked
cite classID className colSpan cols content contentEditable contextMenu controls
controlsList coords crossOrigin data dateTime default defer dir disabled
download draggable encType form formAction formEncType formMethod formNoValidate
formTarget frameBorder headers height hidden high href hrefLang htmlFor
httpEquiv icon id inputMode integrity is keyParams keyType kind label lang list
loop low manifest marginHeight marginWidth max maxLength media mediaGroup method
min minLength multiple muted name noValidate nonce open optimum pattern
placeholder poster preload profile radioGroup readOnly rel required reversed
role rowSpan rows sandbox scope scoped scrolling seamless selected shape size
sizes span spellCheck src srcDoc srcLang srcSet start step style summary
tabIndex target title type useMap value width wmode wrap
7 như là các DOM APIs. Ví dụ như:

<div tabIndex={-1} />      // Just like node.tabIndex DOM API
<div className="Button" /> // Just like node.className DOM API
<input readOnly={true} />  // Just like node.readOnly DOM API

Những thuộc tính này hoạt động tương tự với thuộc tính HTML, với những ngoại lệ liệt kê ở trên.

Một vài thuộc tính DOM được React hỗ trợ như:

accept acceptCharset accessKey action allowFullScreen alt async autoComplete
autoFocus autoPlay capture cellPadding cellSpacing challenge charSet checked
cite classID className colSpan cols content contentEditable contextMenu controls
controlsList coords crossOrigin data dateTime default defer dir disabled
download draggable encType form formAction formEncType formMethod formNoValidate
formTarget frameBorder headers height hidden high href hrefLang htmlFor
httpEquiv icon id inputMode integrity is keyParams keyType kind label lang list
loop low manifest marginHeight marginWidth max maxLength media mediaGroup method
min minLength multiple muted name noValidate nonce open optimum pattern
placeholder poster preload profile radioGroup readOnly rel required reversed
role rowSpan rows sandbox scope scoped scrolling seamless selected shape size
sizes span spellCheck src srcDoc srcLang srcSet start step style summary
tabIndex target title type useMap value width wmode wrap

Tượng tự, tất cả thuộc tính SVG hoàn toàn được hỗ trợ:

accentHeight accumulate additive alignmentBaseline allowReorder alphabetic
amplitude arabicForm ascent attributeName attributeType autoReverse azimuth
baseFrequency baseProfile baselineShift bbox begin bias by calcMode capHeight
clip clipPath clipPathUnits clipRule colorInterpolation
colorInterpolationFilters colorProfile colorRendering contentScriptType
contentStyleType cursor cx cy d decelerate descent diffuseConstant direction
display divisor dominantBaseline dur dx dy edgeMode elevation enableBackground
end exponent externalResourcesRequired fill fillOpacity fillRule filter
filterRes filterUnits floodColor floodOpacity focusable fontFamily fontSize
fontSizeAdjust fontStretch fontStyle fontVariant fontWeight format from fx fy
g1 g2 glyphName glyphOrientationHorizontal glyphOrientationVertical glyphRef
gradientTransform gradientUnits hanging horizAdvX horizOriginX ideographic
imageRendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLength
kerning keyPoints keySplines keyTimes lengthAdjust letterSpacing lightingColor
limitingConeAngle local markerEnd markerHeight markerMid markerStart
markerUnits markerWidth mask maskContentUnits maskUnits mathematical mode
numOctaves offset opacity operator order orient orientation origin overflow
overlinePosition overlineThickness paintOrder panose1 pathLength
patternContentUnits patternTransform patternUnits pointerEvents points
pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits
r radius refX refY renderingIntent repeatCount repeatDur requiredExtensions
requiredFeatures restart result rotate rx ry scale seed shapeRendering slope
spacing specularConstant specularExponent speed spreadMethod startOffset
stdDeviation stemh stemv stitchTiles stopColor stopOpacity
strikethroughPosition strikethroughThickness string stroke strokeDasharray
strokeDashoffset strokeLinecap strokeLinejoin strokeMiterlimit strokeOpacity
strokeWidth surfaceScale systemLanguage tableValues targetX targetY textAnchor
textDecoration textLength textRendering to transform u1 u2 underlinePosition
underlineThickness unicode unicodeBidi unicodeRange unitsPerEm vAlphabetic
vHanging vIdeographic vMathematical values vectorEffect version vertAdvY
vertOriginX vertOriginY viewBox viewTarget visibility widths wordSpacing
writingMode x x1 x2 xChannelSelector xHeight xlinkActuate xlinkArcrole
xlinkHref xlinkRole xlinkShow xlinkTitle xlinkType xmlns xmlnsXlink xmlBase
xmlLang xmlSpace y y1 y2 yChannelSelector z zoomAndPan

Bạn có thể sử dụng thuộc tính tự tạo nhưng phải được viết bằng chữ thường.