Cant clear the value of TextInput in react-native - ios

enter image description herethis problem show in ios,when i use TextInput of react-native,but it can't type Chinese when using soft keyboard,so i modify the code like picture1,but a new problem has arisen,when i enter the key to send ,the value of the TextInput cant clear.
what can i do?enter image desenter code herecription here
<TextareaItem clear={true} type="text" ref="text" value={this.state.meg}
editable={true} disabled={false} onChange={(value) => {
if (Platform.OS =='ios'){
this.meg = value
} else {
this.setState({
meg:value
})}}} />
sendMeg = () => {
let message = ''
if (this.meg !== '')
messahe = this.meg
}else{message = this.state.meg}
this.meg = ''
this.setState({ meg:''})
}
solve with this answer https://github.com/CHANOMA/react-native/pull/3/files#diff-8eb50d68d87e28556c034717cd58a86e

Set this.state.text to initially be an empty string ‘’
Add an actual placeholder to your component and set the value to the string ‘Enter text…’
Add the method submitAndClear to your class and set the component’s onPress prop to this.submitAndClear
Add the prop clearButtonMode='always’ to the <TextInput /> component — this will give you an option to clear the text at any time
The following can be used to clear the text
submitAndClear = () => {
this.props.writeText(this.state.text)
this.setState({
text: ''
})
}
You're good to go!!

Add this code where you want to reset meg field:
this.setState({meg: ''})

Related

Slatejs how to make one specific node non-editable?

I want to set one specific node non-editable by
Transforms.setNodes(editor,{at:[1]},{voids:true})
But it seems not working. Does anyone know how to do it? Thanks!
You need to make your element render with contentEditable prop to false
contentEditable={false} can also add style={{ userSelect: "none" }} to make it non selectable. You can make it dynamic base on the node props and set them them with the trasnformer.
export default function (props: any) {
const { attributes, children, element } = props;
const selected = useSelected()
const focused = useFocused()
return (
<span
{...attributes}
contentEditable={false}
style={{ userSelect: "none" }}
>
{
element.content
?
`【${element.content}】`
: null
}
{children}
</span>
)
}

How to toggle-off the react-native-elements tooltip from another component

I want to manually close the tooltip but there are no documents on the react-native-elements site.
So I look over the tooltip code from github and noticed that it has a toggleTooltip function to toggle. Unfortunately I couldn't make it work.
This is the sample code for the tooltip
import { Tooltip } from 'react-native-elements';
render() {
return (
<Tooltip
ref="tooltip"
popover={
<ComponentTest
toggle={this.refs.tooltip}
>
>
<Text>Click me</Text>
</Tooltip>
);
}
The sample code for the ComponentTest
import { Button } from 'react-native-elements';
toggleOff = () => {
this.props.toggleTooltip;
}
render() {
return (
<Button
title="hide"
type="outline"
onPress={this.toggleOff}
/>
);
}
And this is the function from the tooltip.js that I am trying to use. The full code of the tooltip can found here https://github.com/react-native-training/react-native-elements/blob/master/src/tooltip/Tooltip.js
toggleTooltip = () => {
const { onClose } = this.props;
this.getElementPosition();
this.setState(prevState => {
if (prevState.isVisible && !isIOS) {
onClose && onClose();
}
return { isVisible: !prevState.isVisible };
});
};
i am new to react-native and was trying to use tooltip, what i found out that whenever u click inside the component which is popovered , it navigates to whatever onpress function u have written on that particular component and the tooltip doesn't closes,,it also remain mounted when u navigate to other pages,,one solution to it is that use react-native-popup-menu.its the best that we can use for now as a tooltip https://www.npmjs.com/package/react-native-popup-menu
It may be a stupid solution, but did you tried using this.props.toggleTooltip() ?
OH , and ref is not a string anymore, it's a function
<Tooltip
ref={ref => (this.tooltip = ref)}
popover={
<ComponentTest
toggle={this.tooltip}
>
>
On line 191 of Tooltip.js:
<TouchableOpacity onPress={this.toggleTooltip}>
{this.renderContent(true)}
</TouchableOpacity>
and in the definition of renderContent:112 on line 137, it is rendered your popover:
Thus wherever you touch in your popover will make it disappear. I don't know how to disable this behaviour, but I still want to know if and how the visibility of the popover can be controlled from the Tooltip's child element at least.
Just set its style to display:'none' after you touch your popover.
maybe try this way:
state = { theDisplay: 'flex' };
...
componentDidUpdate(prevProps: any) {
if (!prevProps.isFocused && this.props.isFocused) {
this.setState({ theDisplay: 'flex' });
}
}
...
<Popover.Item
value={'response'}
onSelect={() => {
this.setState({ theDisplay: 'none' });
navigate('NoticeResponse', { id: item.id });
}}>
<Text style={styles.toolsItem}>已读信息</Text>
</Popover.Item>
This is my own way of dealing with it. I hope it will help you.
DISCLAIMER I used the ref example in order to get my code to work, but it's something like this:
const tooltipRef = useRef(null);
const foo = (event, index) => {
event.stopPropagation();
tooltipRef.current.toggleTooltip()
}
...
<Tooltip
height={200}
ref={tooltipRef}
popover={<TouchableOpacity onPress={(event) => foo(event, index)}
/>
I had originally tried to implement this by simply using the tooltipRef.current.toggleTooltip() like in the example but it never ended up working because the event was propagating and continuing to toggle it on its own (effectively toggling it twice).
Without any 3rd party library, simple tooltip for both iOS and android can be implemented as follows:
onPress={() =>
Alert.alert("My Title", "My Msg", [], {
cancelable: true
})
}
React native elements documentation show that we can manually turn off the tooltip.
Docs
Store a reference to the Tooltip in your component by using the ref prop provided by React
const tooltipRef = useRef(null);
...
<Tooltip
ref={tooltipRef}
...
/>
Then you can manually trigger tooltip from anywhere for example when screen loads:
useEffect(() => {
tooltipRef.current.toggleTooltip();
}, []);

How to disable Chart JS tooltip when there is no value?

I am using Chart JS v.1.0.2. When I have one line and missing data, the tooltip shows x-label.
Does anyone know how to disable the tooltip when the point value is null?
Thanks very much!
If you don't mind a few console messages you can throw an error to exit out of the tooltip method for null values, like so
var myLineChart = new Chart(ctx).Line(data, {
tooltipTemplate: function (d) {
if (d.value === null)
throw '';
else
// else return the normal tooltip text
return d.label + ': ' + d.value;
}
});
The alternative would be to extend the chart or write a custom tooltips function
Fiddle - http://jsfiddle.net/y4zunrx6/
Using chart.js 2.3.0 and angular-chart.js 1.1.1, I solved the problem globally by resolving the ChartJsProvider provider in my angular.module('shared').config(...) function and specifying a custom label callback for the tooltips option:
ChartJsProvider.setOptions({
tooltips: {
enabled: true,
//mode: 'single',
callbacks: {
label: function (tooltipItem, data) {
const tooltip = data.datasets[tooltipItem.datasetIndex];
const value = tooltip.data[tooltipItem.index];
return value === 0 ? null : tooltip.label + ': ' + value;
}
}
}
});
By returning null the tooltip is not shown for that specific tooltipItem.
Reference: Chart.js Tooltip Configuration
I wanted to disable the tooltip all times. The version I'm using is 2.1.6, and I did it like this:
var options = {
tooltips : {
enabled: false
}
};
Note: This will not display tool-tip at all, use it only when you want to disable the tool-tip appearing.
Better approach is to customize tooltip template to show no data :
tooltipTemplate: "<%if (label && value){%><%=label%>: <%= value %><%} else {%> No data <%}%>"

Use jQuery to check and see if div element is empty

Below is the code I'm using to place a blur event on a text box in my ASP MVC 3 view. The code works fine if #MailingState is empty, however it cannot tell if #channelName is empty.
For example, if #channelName is empty but #MailingState is not, then when I place a value in #MailingZip the getDrmTerritory Ajax call is fired off every time.
Here is the jQuery
$('#MailingZip').blur(function () {
if ($('#AlignmentM').is(':checked')) {
if ($('#MailingState').val() != "" && $('#channelName').html() != "") {
getDrmTerritory($('#MailingZip').val(), $('#MailingState').val(), $('#channelName').html());
}
}
});
and here is the HTML for the #channelName segment it is checking
<div id="channelName" class="M-display-field">
#*this will be updated via ajax from Market Segment *#
#Html.DisplayFor(model => model.Channel, new { style = "margin-left: 300px;" } )
</div>
The section mentioned in the comments is updated via another jQuery method that looks like this
function ChangeChannel() {
//this function called if Market Segment changes, to update the channel
var pendistcode = document.getElementById('Pendist');
if (pendistcode == null) alert('Error: Cannot find Market Segment control');
//alert('!pendistcode value is ' + pendistcode.value);
$.ajax({
type: 'POST',
url: '/AgentTransmission/GetChannel/',
data: { pendist: pendistcode.value },
success: function (data) {
// alert("success: " + data);
$('#channelName').html(data);
$('#Channel').val(data);
},
error: function (data) {
alert("failure to obtain Channel name");
}
});
CheckTerritory('channel');
} //end ChangeChannel
That jQuery method (ChangeChannel) appends text to the channelName div which, when rendered with a value in it, looks like this
Here is the HTML you get when you inspect the Life Sales from that picture
You can check if #channelName is empty or not like this:
if ( $('#channelName').is(':empty') )
and combine with your code like this:
if ($('#MailingState').val() != "" && !$('#channelName').is(':empty'))
I put in an alert statment to find out channelName's length and it came back with 35, so there must obviously be some white space that gets rendered each time. I had to change the statement to the following to trim out the whitespace and add the variable to the condition.
var channel = $.trim($('#channelName').html());
if ($('#MailingState').val() != "" && channel != "")

Has any one used client_side_validations gem with Chosen.js dropdown?

I am using chosen.js (http://harvesthq.github.com/chosen/). I was wondering if anyone has been able to use chosen select boxes and client_side_validations together.
The issue is that when we use chosen it hides the original select element and renders its own dropdown instead, and when we focus out the validation isn't called and also when the validation message is shown it is shown with the original select element so positioning of the error isnt also correct.
What could be a good way to handle this, My be we can change some code inside ActionView::Base.field_error_proc which currently looks something like
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
unless html_tag =~ /^<label/
%{<div class="field_with_errors">#{html_tag}<label for="#{instance.send(:tag_id)}" class="message">#{instance.error_message.first}</label></div>}.html_safe
else
%{<div class="field_with_errors">#{html_tag}</div>}.html_safe
end
end
Any ideas ?
Edit 1:
I have the following solution that is working for me now.
applied a class "chzn-dropdown" to all my selects that were being displayed by chosen
used the following callback provided by client_side_validations Gem
clientSideValidations.callbacks.element.fail = function(element, message, callback) {
if (element.data('valid') !== false) {
if(element.hasClass('dropdown')){
chzn_element = $('#'+element.attr('id')+'_chzn');
console.log(chzn_element);
chzn_element.append("<label class='message-chzn'>"+message+"</label>");
}
else{
callback();
}
}
}
About the issue with the validation not running at all when the chosen selection changes you can try this:
selectbox.change(function() { setTimeout(function() { selectbox.focusout() }) });
I'm still looking for a solution about the validation message positioning because I'd really love to avoid tampering with the client side validations javascript.
EDIT:
It seems this is a good solution after all, to keep closer to the client side validations api I came up with the following (for whom it may concern):
var settings = {
type: 'ActionView::Helpers::FormBuilder',
input_tag: '<div class="field_with_errors"><span id="input_tag" /><label class="message validationError" /></div>'
};
clientSideValidations.callbacks.element.fail = function (element, message, addError) {
if ($(element).data('chosen') != null) {
var chosen = $('#' + element.attr('id') + '_chzn');
clientSideValidations.formBuilders[settings.type].add(chosen, settings, message);
// Point the label back to the select box
$('label[for="' + chosen.attr('id') + '"]').attr('for', element.attr('id'));
// Mark it as invalid
chosen.data('valid', false);
} else {
addError(element, message);
}
};
clientSideValidations.callbacks.element.pass = function (element, removeError) {
if (element.data('chosen') != null) {
var chosen = $('#' + element.attr('id') + '_chzn');
clientSideValidations.formBuilders[settings.type].remove(chosen, settings);
// Un-mark it from invalid
chosen.data('valid', null);
} else {
removeError(element);
}
};
Note that I use a data attribute (data-chosen) for initialising select-boxes with chosen. Also for a label click to open chosen to work, I explicitly open the list box on label click:
// element is the select box
// Delegate click event from related labels to element (this is already done on "good" browsers)
$('label[for="' + element.attr('id') + '"]').click(function() { element.click() });
// Delegate click event on original element and any related labels to open the list
$(element).click(function() { setTimeout(function() { element.trigger('liszt:open'); }, 0); });
clientSideValidations.callbacks.element.fail = function(element, message, callback){
if(element.data("valid") !== false) {
callback();
if(element.is("select") && $("#" + element.attr("id") + "_chzn").length > 0){
element.parent().prepend($("#" + element.attr("id") + "_chzn"));
}
}
}
Try this:
Tell the gem that you want to validate select tags:
ClientSideValidations.selectors.inputs += ', select';
Force validation when Chosen's dropbox changes:
$('#form_field').chosen().change(function(e) {
var settings = window.ClientSideValidations.forms[this.form.id];
$(this).isValid(settings.validators);
});
Since Chosen hides the field, you will need to enable validation for that field explicitly in the view:
<%= form_for ..., :validate => true do |f| %>
...
<%= f.validate :form_field %>
...
<% end %>

Resources